Unit-5 C QB With Ans
Unit-5 C QB With Ans
Example:
struct employee {
int eno;
char ename[20];
char eadd[100];
float bs;
};
2.Declare the structure before using the program by Specifying its member
variables along with the Datatypes and use the STRUCT keyword to declare The
structure in C.
Program:
#include <stdio.h>
#include <string.h>
// Declare the structure using the struct keyword
struct Person {
// Member variables or fields
char name[50];
int age;
float height;
};
int main()
{
// Declare a variable of type Person
struct Person person1;
// Access and assign values to the members of the structure
strcpy(person1.name, "John Doe");
person1.age = 25;
person1.height = 5.9;
// Display the information
printf("Person Information:\n");
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.2f feet\n", person1.height);
return 0;
}
Output: Person Information:
Name: John Doe
Age: 25
Height: 5.90 feet
The structure Person is declared at the beginning of the program before the main
function.
• Inside the structure definition, member variables (name,age, and height) are
specified with their respective data types.
• The main function then uses this declared structure to define a variable person1
of type struct Person and manipulates its members.
Program:
#include <stdio.h>
struct Address {
int streetNo;
char city[30];
char state[30];
int pinCode;
};
struct Employee {
char name[50];
struct Address address; // Nested structure
};
int main() {
struct Employee emp;
// Input employee details
printf("Enter employee name: ");
scanf("%s", emp.name);
printf("Enter street number: ");
scanf("%d", &emp.address.streetNo);
printf("Enter city: ");
scanf("%s", emp.address.city);
printf("Enter state: ");
scanf("%s", emp.address.state);
printf("Enter pin code: ");
scanf("%d", &emp.address.pinCode);
// Output employee details
printf("\nEmployee Details:\n");
printf("Name: %s\n", emp.name);
printf("Address: Street No: %d, City: %s, State: %s, Pin Code: %d\n",
emp.address.streetNo, emp.address.city, emp.address.state,
emp.address.pinCode);
return 0;
}
OUTPUT:
Enter employee name: John
Enter street number: 123
Enter city: Springfield
Enter state: Illinois
Enter pin code: 62704
Employee Details:
Name: John
Address: Street No: 123, City: Springfield, State: Illinois, Pin Code: 62704
Program:
#include <stdio.h>
// Define a union to represent a complex number
union Complex {
struct {
float real; // Real part
float imag; // Imaginary part
} parts;
};
// Function to add two complex numbers
union Complex addComplex(union Complex c1, union Complex c2)
{
union Complex result;
result.parts.real = c1.parts.real + c2.parts.real;
result.parts.imag = c1.parts.imag + c2.parts.imag;
return result;
}
// Function to display a complex number
void displayComplex(union Complex c)
{
printf("%.2f + %.2fi\n", c.parts.real, c.parts.imag);
}
int main()
{
union Complex c1, c2, sum;
// Input for first complex number
printf("Enter the real part of the first complex number: ");
scanf("%f", &c1.parts.real);
printf("Enter the imaginary part of the first complex number: ");
scanf("%f", &c1.parts.imag);
// Input for second complex number
printf("Enter the real part of the second complex number: ");
scanf("%f", &c2.parts.real);
printf("Enter the imaginary part of the second complex number: ");
scanf("%f", &c2.parts.imag);
// Add the two complex numbers
sum = addComplex(c1, c2);
// Display the result
printf("\nThe sum of the two complex numbers is: ");
displayComplex(sum);
return 0;
}
Input:
Enter the real part of the first complex number: 3
Enter the imaginary part of the first complex number: 4
Enter the real part of the second complex number: 1
Enter the imaginary part of the second complex number: 2
Output: The sum of the two complex numbers is: 4.00 + 6.00i
5.Differentiate between structure and a union.
Content Structure(struct) Union(union)
1.Memory Allocation: Allocates memory for Allocates enough
each member memory to hold the
individually. Members largest member. All
are stored in separate members share the same
memory locations. Size of memory space.
a structure is the sum of Size of a union is
the sizes of its members, determined by the size of
possibly with padding. its largest member.
2.Initialization of Each variable of the All variables of the union
Multiple Variables: structure type gets its own share the same memory
copy of the Member space.
variables Initializing one member
Initialization involves affects the values of all
assigning values to each other members Because
member Individually. they share the same
memory.
3.Storage of Data Suitable when you want Useful when you want to
Types: to group related but save memory by sharing
distinct pieces of the same Space for
Information. Each different types of data.
member retains its own Only one member can be
memory space. accessed at a time. All
Members can be of members share the same
different sizes and types. memory space, and
changing the Value of one
member may affect
others.
4.Accessing Members: Accessing members is Only one member can be
straightforward by using accessed at a time.
the dot (.) Operator. Members share the same
memory, and accessing
one
Members can be member May overwrite
accessed simultaneously the value of another.
without interference.
// Structure example
struct Person {
char name[20];
int age;
};
//Union example
union Data {
int intValue; float
floatValue;
};
int main() {
//Structure usage
struct Person person1;
person1.age = 25;
//Union usage
union Data data1;
data1.intValue = 42;
printf(“Structure Size: %zu\n”, sizeof(person1)); // Size of
struct printf(“Union Size: %zu\n”, sizeof(data1)); //Size of
union
return 0;
}
output
Structure Size: 24
Union Size: 4
Program:
#include <stdio.h>
#include <string.h>
// Define a structure for Date of Birth
struct Date {
int day;
int month;
int year;
};
// Define a structure for Student record
struct Student {
char name[50];
struct Date dob; // Nested structure for Date of Birth
float marks;
};
// Function to sort students by marks in descending order
void sortStudents(struct Student students[], int n)
{
struct Student temp;
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (students[i].marks < students[j].marks)
{
temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}
}
int main()
{
struct Student students[10];
// Input data for 10 students
for (int i = 0; i < 10; i++)
{
printf("Enter details for Student %d:\n", i + 1);
printf("Name: ");
scanf(" %[^\n]", students[i].name); // Read string with spaces
printf("Date of Birth (DD MM YYYY): ");
scanf("%d %d %d", &students[i].dob.day, &students[i].dob.month,
&students[i].dob.year);
printf("Total Marks: ");
scanf("%f", &students[i].marks);
}
// Sort students by marks in descending order
sortStudents(students, 10);
// Display student records
displayStudents(students, 10);
return 0;
}
Rank 2:
Name: Alice
Date of Birth: 15-06-2005
Marks: 85.50
...
8.Describe the differences between text mode and binary mode When opening files
in C. Include code examples for both modes And explain when each mode is
preferable.
1. Text Mode:
• In text mode, files are treated as sequences of lines, where each Line ends with a
special character (commonly ‘\n’ in Unix-like Systems or ‘\r\n’ in Windows).
• Text mode may perform newline translation, converting between the
platformspecific newline representation and the standard ‘\n’ Character.
• Suitable for working with plain text files where newline Characters might need
translation.
Text Mode Example:
#include <stdio.h>
int main()
{
FILE *textFile;
//Opening a file in text mode for writing
textFile = fopen(“text_file.txt”, “wt”);
if (textFile == NULL)
{
perror(“Error opening file”);
return 1;
}
// Writing to the file
fprintf(textFile, “Hello, this is a text file.\
n”);
//Closing the file
fclose(textFile);
return 0;
}
Output:
Error opening file
2. Binary Mode:
• In binary mode, files are treated as a sequence of bytes with no translation of
newline characters.
• No newline translation occurs in binary mode.
• Suitable for non-text files like images, audio, executables, or any data that
doesn’t adhere to text file conventions.
Binary Mode Example:
#include <stdio.h>
int main()
{
FILE *binaryFile;
//Opening a file in binary mode for
writing
binaryFile = fopen(“binary_file.bin”, “wb”);
if (binaryFile == NULL)
{
perror(“Error opening file”);
return 1;
}
//Writing binary data to the file
int data[] = {1, 2, 3, 4, 5};
fwrite(data, sizeof(int), 5, binaryFile);
//Closing the file
fclose(binaryFile);
return 0;
}
Output:
Error opening file
Scenarios:
Text Mode:
• Use text mode when working with files that contain human-readable text, such as
configuration files or simple Data files.
• Preferred for portability across different platforms Because it handles newline
character translation.
Binary Mode:
• Use binary mode when working with non-text files like Images, audio, or
executable files.
• Preferred when precise control over the data is needed,And newline translation is
not desired.
Important Note:
On most systems, text and binary modes may behave the same Way. However, on
platforms with different newline conventions (e.g., Windows and Unix), text mode
may perform newline Translation. It’s essential to consider these platform
differences When working with files in C.
9.Create a union named “Color” that can represent a color using Either RGB
values (Red, Green, Blue) or a hexadecimal color code.Provide a code example that
demonstrates how to use this union for Representing colors in different formats
and explain its versatility in Handling multiple representations of color.
Program:
#include <stdio.h>
// Define the Color union
union Color {
struct RGB {
unsigned char red;
unsigned char green;
unsigned char blue;
} rgb; // Nested structure for RGB values
unsigned int hex; // Hexadecimal color code
};
int main()
{
union Color color;
// Represent color using RGB values
color.rgb.red = 255;
color.rgb.green = 165;
color.rgb.blue = 0;
// Display color in RGB format
printf("Color in RGB format: Red=%d, Green=%d, Blue=%d\n",
color.rgb.red, color.rgb.green, color.rgb.blue);
// Note: Writing to the hex field will overwrite RGB values
color.hex = 0xFFA500;
// Display color in hexadecimal format
printf("Color in Hexadecimal format: 0x%X\n", color.hex);
return 0;
}
Output:
Color in RGB format: Red=255, Green=165, Blue=0
Color in Hexadecimal format: 0xFFA500
10.Discuss the significance of the feof() function in the context of file Handling.
Provide a code snippet that demonstrates the use of feof() and explains its role in
file processing.
Answer:
The feof() function in C is a library function that checks whether the end-of-file
indicator associated with a file stream has been set. It is often used in the context of file
handling to determine if the reading or writing operation has reached the end of the file.
Significance of feof() Function:
End-of-File Check:
Feof() is used to check if the current position indicator of a file Stream has reached the
end of the file. It returns a non-zero value if the end-of-file indicator is set, indicating
that there are no more characters to read.
Preventing Reading Past End-of-File:
Feof() is commonly used in conjunction with file input functions Like fscanf or fgetc to
prevent reading past the end of a file.It helps avoid undefined behavior that can occur
when attempting To read from a file that has already reached its end.
Loop Termination Condition:
It is often used in loops to control the termination condition when Reading from a file.
The loop continues until feof() returns a non-Zero value, indicating the end of the file.
Example that demonstrates the use of feof() in the Context of reading from a file:
#include <stdio.h>
int main()
{
FILE *file;
char character;
// Open a file for reading
file = fopen(“sample.txt”, “r”);
if (file == NULL)
{
perror(“Error opening file”);
return 1;
}
// Read characters until the end of the file
while (!feof(file))
{
character = fgetc(file);
// Check for end-of-file or error
if (feof(file))
{
printf(“Reached end of file.\n”);
}
else if (ferror(file))
{
perror(“Error reading file”);
break;
}
else
{
// Process the character (example: print it)
putchar(character);
}
}
// Close the file
fclose(file);
return 0;
}
Output:
Hello, this is a sample file.
Reached end of file.
Or
Error opening file: No such file
or directory
PARTC
1.Show the need for the structure data type in C programming with examples and
how the structures facilitate the creation of complex data types and improve code
organization.
In C programming, a structure is a composite data type that allows you to group
variables of different data types under a single name. This is particularly useful when
dealing with complex data and improves code organization by encapsulating related
information into a single unit. an example to illustrate the need for structures and how
they facilitate the creation of complex data types:
Program:
#include <stdio.h>
// Define a structure to represent a Point in 2D space
struct Point {
int x;
int y;
};
// Define a structure to represent a Rectangle
struct Rectangle {
struct Point topLeft;
struct Point bottomRight;
};
// Function to calculate the area of a rectangle
int calculateArea(struct Rectangle rect)
{
int width = rect.bottomRight.x - rect.topLeft.x;
int height = rect.bottomRight.y - rect.topLeft.y;
return width * height;
}
int main()
{
// Create two Point structures
struct Point p1 = {1, 2};
struct Point p2 = {4, 5};
// Create a Rectangle structure using the Points
struct Rectangle myRect = {p1, p2};
// Calculate and print the area of the rectangle
int area = calculateArea(myRect);
printf("Area of the rectangle: %d\n", area);
return 0;
}
Output: Area of the rectangle: 9
A union in C programming is a special data type that allows different data types
to occupy the same memory location. In other words, all members of a union
share the same memory address. However, at any given time, a union can store
only one of its members, and the size of the union is determined by the largest
member.
Unions are useful when you need to store data in different formats but only need
to store one format at a time. For example, a union could be used to represent a
value that can either be an integer or a floating-point number, but not both
simultaneously.
Properties of Unions:
1. Memory Sharing: All members share the same memory location, which means
only one member can store a value at a time.
2. Memory Size: The size of the union is the size of its largest member.
3. Accessing Members: Since all members share the same memory location,
modifying one member will overwrite the value of the other members.
Program:
#include <stdio.h>
// Define a union to store either an integer, a float, or a character
union Data {
int i;
float f;
char c;
};
int main()
{
// Declare a union variable
union Data data;
// Initialize and access union members
data.i = 42;
printf("Union data (int): %d\n", data.i);
data.f = 3.14;
printf("Union data (float): %.2f\n", data.f); // Overwrites previous 'i'
data.c = 'A';
printf("Union data (char): %c\n", data.c); // Overwrites previous 'f'
Memory Allocation: The memory allocated for a structure is the sum of the Memory
required by each member.
Member Access: Members of a structure are accessed independently using The dot (.)
operator.
Example Use Case: Structures are suitable when you need to group related But
distinct pieces of information together. For example, representing a Point in 2D space
with x and y coordinates.
#include <stdio.h>
struct point {
int x;
int y;
};
int main()
{
struct Point p1 = {1, 2};
printf(“Coordinates: (%d, %d)\n”, p1.x,
p1.y);
return 0;
}
Unions in C:
Definition: A union is a composite data type that allows you to define a Variable with
multiple members, but only one member can hold a value at a Time. All members in a
union share the same memory space.
Declaration:
Union Data {
int intValue;
float floatValue;
char stringValue[20];
};
Initialization:
Union Data myUnion = {42}; // Initializing the first member (intValue)
Memory Allocation: The memory allocated for a union is determined by the size of its
largest member.
Member Access: Members of a union are accessed independently using the Dot (.)
operator. However, only the member most recently assigned a value Should be
accessed.
Example Use Case: Unions are suitable when you want to represent a Single value that
could be of different types at different times.
For example,Representing a variable that could be an integer, float, or string
#include <stdio.h>
#include <string.h> // For strcpy
// Define a union
union Data {
int intValue;
float floatValue;
char stringValue[20];
};
int main() {
// Initialize the first member (intValue)
union Data myUnion = {42};
printf("Integer Value: %d\n", myUnion.intValue);
// Assign a value to floatValue (overwrites intValue)
myUnion.floatValue = 3.14;
printf("Float Value: %.2f\n", myUnion.floatValue);
// Assign a string value (overwrites floatValue)
strcpy(myUnion.stringValue, "Hello, Union!");
printf("String Value: %s\n", myUnion.stringValue);
return 0;
}
Output: Integer Value: 42
Float Value: 3.14
String Value: Hello, Union!
Comparison:
Memory Usage:
• Structures allocate memory for each member independently, resulting in the Sum
of their sizes.
• Unions share the same memory space for all members, and the size is Determined
by the largest member.
Access Patterns:
• Structure members are accessed independently, and all members can be used
simultaneously.
• Only one member of a union should be accessed at a time, based on the Most
recent assignment.
Use Cases:
• Use structures when you need to represent a collection of different types of Data
or when each member should store distinct information.
• Use unions when you want to represent a single value that can be of Different
types at different times or when memory efficiency is crucial.
Flexibility:
• Structures offer more flexibility in terms of storing and accessing multiple Pieces
of information simultaneously.
• Unions are more memory-efficient but limit simultaneous access to a single
Member.
#include <stdio.h>
// Define the Employee structure
struct Employee {
int employeeID;
char name[50];
float salary;
};
int main()
{
// Create an array of Employee structures with sample data
struct Employee employeeDatabase[5] = {
{101, "John Doe", 50000.0},
{102, "Jane Smith", 60000.0},
{103, "Bob Johnson", 75000.0},
{104, "Alice Williams", 55000.0},
{105, "Charlie Brown", 70000.0}
};
With Buffering:
#include <stdio.h>
int main()
{
FILE *file = fopen("buffered_example.txt",
"w");
if (file != NULL) {
// Enable buffering explicitly
setvbuf(file, NULL, _IOFBF, 4096); // Write large amount of data
to the file
for (int i = 0; i < 1000000; ++i)
{
fprintf(file, "This is line %d\n", i);
}
fclose(file);
}
else
{
printf("Unable to open the file.\n");
}
return 0;
}
Output: Unable to open the file.
Without Buffering:
#include <stdio.h>
int main()
{
FILE *file = fopen("unbuffered_example.txt",
"w");
if (file != NULL)
{
// Disable buffering explicitly
setvbuf(file, NULL, _IONBF, 0); // Write large amount of data to the file
for (int i = 0; i < 1000000; ++i)
{
fprintf(file, "This is line %d\n", i);
}
fclose(file);
}
else
{
printf("Unable to open the file.\n");
}
return 0;
}
Output: Unable to open the file.
In both examples, a large amount of data is written to a file. The first example explicitly
enables buffering, while the second example disables buffering.In practice, the buffering
mode is often set implicitly, and the C library handles it automatically. Explicitly setting
buffering with setvbuf is shown here for illustrative purposes.