0% found this document useful (0 votes)
68 views33 pages

Unit-5 C QB With Ans

C programming notes for engineering

Uploaded by

ragulooppll
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views33 pages

Unit-5 C QB With Ans

C programming notes for engineering

Uploaded by

ragulooppll
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

UNIT 5

QUESTION BANK ANSWER KEY


231CS111 PROGRAMMING
Part-B
1.State the meaning of the root word Struct and give the syntax for structure
definition
Structure Definition
Structure is a user defined data type which hold or store heterogeneous/different types
data item or element in a single variable. It is a Combination of primitive and derived
data type.
or
A structure is a collection of one or more data items of different data types, grouped
together under a single name.
Variables inside the structure are called members of structure.
Each element of a structure is called a member.
struct keyword is used to define/create a structure. struct define a new data type
which is a collection of different type of data.
Syntax
struct structure_name /tag name
{
data_type member1;
data_type member2;
data_type member n;
};

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.

3.Consider C a program to store the address of an entity employee in a structure


and the attributes address may also have the sub parts has street no, city, state and
pin code. Hence store the address of the employee in to a separate structure and
nest the structure address in to the structure employee.

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

4.Write a C program that uses a union to represent a complex number. The


program should include functions to perform the following tasks:
 Add two complex numbers.
 Display the result of the addition.

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

6.Construct a C program using structure to store employee Information such as


employee id, employee name, employee Salary, employee department, employee
address.
#include <stdio.h>
#include <string.h> // Include string.h for strcpy
// Define the structure for employee information
struct Employee {
int employeeId;
char employeeName[50];
float employeeSalary;
char employeeDepartment[50];
char employeeAddress[100];
};
int main()
{
// Declare a variable of type Employee
struct Employee employee1;
// Assign values to the members of the employee structure
employee1.employeeId = 101;
strcpy(employee1.employeeName, "JohnDoe");
employee1.employeeSalary = 50000.00;
strcpy(employee1.employeeDepartment, "IT");
strcpy(employee1.employeeAddress, "123 Main St, Cityville, State");
// Display the employee information
printf("Employee Information:\n");
printf("Employee ID: %d\n", employee1.employeeId);
printf("Name: %s\n", employee1.employeeName);
printf("Salary: $%.2f\n", employee1.employeeSalary);
printf("Department: %s\n", employee1.employeeDepartment);
printf("Address: %s\n", employee1.employeeAddress);
return 0;
}
Output:
Employee Information:
Employee ID: 101
Name: JohnDoe
Salary: $50000.00
Department: IT
Address: 123 Main St, Cityville, State
7.Create a structure Student record that includes the student’s Name, date of birth,
and total marks obtained. Use a separate Structure to represent the date of birth.
Develop a program to input Data for 10 students and display them in descending
order of their Marks (rank-wise).

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;
}
}
}
}

// Function to display student records


void displayStudents(struct Student students[], int n)
{
printf("\nRank-wise Student Records:\n");
for (int i = 0; i < n; i++)
{
printf("Rank %d:\n", i + 1);
printf("Name: %s\n", students[i].name);
printf("Date of Birth: %02d-%02d-%04d\n", students[i].dob.day,
students[i].dob.month, students[i].dob.year);
printf("Marks: %.2f\n\n", students[i].marks);
}
}

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;
}

Input: Enter details for Student 1:


Name: Alice
Date of Birth (DD MM YYYY): 15 06 2005
Total Marks: 85.5
...
Enter details for Student 10:
Name: John
Date of Birth (DD MM YYYY): 22 08 2004
Total Marks: 90.0
Output:
Rank-wise Student Records:
Rank 1:
Name: John
Date of Birth: 22-08-2004
Marks: 90.00

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

2.Create a structure called ‘Employee' that stores information about an employee,


including employee ID, name, and salary. Declare an array of this structure to
represent a list of employees. Write a C program to calculate the average salary of
all employees and display the details of employees whose salary is above the
average.
The program that defines a structure named “Employee" and demonstrates how to
calculate the average salary of employees and display details of employees with a salary
above the average.
Program:
#include <stdio.h>
// Define the Employee structure
struct Employee {
int employeeID;
char name[50];
float salary;
};
int main()
{
// Declare an array of Employee structures
struct Employee employeeList[5];
// Populate the array with sample data
employeeList[0] = (struct Employee){101, "John Doe", 50000.0};
employeeList[1] = (struct Employee){102, "Jane Smith",
60000.0};
employeeList[2] = (struct Employee){103, "Bob Johnson",
75000.0};
employeeList[3] = (struct Employee){104, "Alice Williams",
55000.0};
employeeList[4] = (struct Employee){105, "Charlie Brown",
70000.0};
// Calculate the average salary
float totalSalary = 0.0;
for (int i = 0; i < 5; i++)
{
totalSalary += employeeList[i].salary;
}
float averageSalary = totalSalary / 5; //
Display the average salary printf("Average
Salary: %.2f\n", averageSalary);
// Display details of employees with salary above the average
printf("Employees with salary above the average:\n");
for (int i = 0; i < 5; i++)
{
if (employeeList[i].salary > averageSalary)
{
printf("ID: %d, Name: %s, Salary: %.2f\n",
employeeList[i].employeeID, employeeList[i].name,
employeeList[i].salary);
}
}
return 0;
}
Output: Average Salary: 62000.00
Employees with salary above the average:
ID: 103, Name: Bob Johnson, Salary: 75000.00
ID: 105, Name: Charlie Brown, Salary: 70000.00

3.Design the concept of nested structures in C programming. Provide a detailed


example illustrating the declaration, initialization, and member access of a
structure with in a structure.Discuss the advantages and use cases of using nested
structures in code development.
In C programming, nested structures refer to the concept of defining one structure inside
another. This allows you to create more complex data structures by organizing related
information in a hierarchical manner. an example that illustrates the declaration,
initialization, and member access of a structure within a structure:
Programm:
#include <stdio.h>
// Define the Address structure
struct Address {
char street[50];
char city[50];
char state[20];
int zipCode;
};
// Define the Employee structure with a nested Address
structure
struct Employee {
int employeeID;
char name[50];
float salary;
struct Address employeeAddress; // Nested structure
};
int main() {
// Declare and initialize an Employee structure with a nested Address structure
struct Employee emp1 = {
101,
"John Doe",
50000.0,
{"123 Main St", "Anytown", "CA", 12345} // Nested structure initialization
};
// Access and display information using nested structure
members
printf("Employee ID: %d\n", emp1.employeeID);
printf("Name: %s\n", emp1.name);
printf("Salary: %.2f\n", emp1.salary);
printf("Address: %s, %s, %s %d\n", emp1.employeeAddress.street,
emp1.employeeAddress.city, emp1.employeeAddress.state,
emp1.employeeAddress.zipCode);
return 0;
}
Output:
Employee ID: 101
Name: John Doe
Salary: 50000.00
Address: 123 Main St, Anytown, CA 12345

Advantages and Use Cases of Nested Structures:


Organized Data: Nested structures provide a way to organize related data In a
structured and hierarchical manner. In the example, the address Information is logically
grouped within the Address structure, making the Code more organized.
Modularity and Reusability: The use of nested structures promotes Modularity. You
can reuse the Address structure in other parts of your code, Maintaining a consistent
data structure for addresses.
Readability and Maintainability: Code becomes more readable and Maintainable as it
reflects the natural organization of data. It’s easier to Understand the relationships
between different pieces of information.
Encapsulation: Nested structures encapsulate related data, providing a level Of
abstraction. This encapsulation helps in hiding implementation details and allows for
more straightforward manipulation of data.
Complex Data Structures: Nested structures are particularly useful when Dealing with
complex data structures, such as a structure representing an Employee with nested
structures for different aspects like address, Department, etc.

4.Discuss the concept of a union in C programming. Provide a comprehensive


example that demonstrates how to declare, initialize,and access members of a
union. Also, highlight the key differences between unions and structures, and
explain the appropriate scenarios for using each .

 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'

// Show the size of the union


printf("Size of union: %zu bytes\n", sizeof(data));
return 0;
}
Output: Union data (int): 42
Union data (float): 3.14
Union data (char): A
Size of union: 4 bytes

Differences Between Union and Structure:


Feature Union Structure
Memory All members share the same memory Each member has its own memory
Allocation location location
Size Size of the largest member Sum of sizes of all members
Only one member can store a value at All members can store values at th
Access
a time same time
When you need to store different data When you need to store multiple
Use Case
types, but only one at a time pieces of data at the same time

When to Use Each:


• Use structures when you need to store and access multiple pieces of related
Information simultaneously.
• Use unions when you want to save memory by representing a value that can Be of
different types at different times.

5.Compare and contrast structures and unions in C programming.Provide a


detailed explanation of their similarities, differences, and use cases. Illustrate your
answer with code examples that highlight scenarios where structures are more
appropriate and where unions excel.
Structures in C:
Definition: A structure is a composite data type that allows you to gro
up variables of different types under a single name. Each member in a structure
Has its own memory space. Declaration:
struct Point {
int x;
int y;
};
Initialization:
struct Point p1 = {1, 2};

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.

6.Write a C program that uses structures to represent a simple employee Database.


Each employee should have attributes like employee ID,Name, and salary.
Implement functions to:
1. Identify the employee with the highest salary.
2. Calculate the average salary.
3. Display the details of all employees.
Demonstrate the program by creating an array of employee structures With
sample data.

#include <stdio.h>
// Define the Employee structure
struct Employee {
int employeeID;
char name[50];
float salary;
};

// Function to find the employee with the highest salary


struct Employee findHighestSalary(struct Employee employees[], int size)
{
struct Employee highestSalaryEmployee = employees[0];
for (int i = 1; i < size; ++i)
{
if (employees[i].salary > highestSalaryEmployee.salary)
{
highestSalaryEmployee = employees[i];
}
}
return highestSalaryEmployee;
}

// Function to calculate the average salary


float calculateAverageSalary(struct Employee employees[], int size)
{
float totalSalary = 0.0;
for (int i = 0; i < size; ++i)
{
totalSalary += employees[i].salary;
}
return totalSalary / size;
}

// Function to display details of all employees


void displayEmployeeDetails(struct Employee employees[], int size)
{
printf("Employee Details:\n");
for (int i = 0; i < size; ++i)
{
printf("ID: %d, Name: %s, Salary: %.2f\n",
employees[i].employeeID, employees[i].name,
employees[i].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}
};

// Find the employee with the highest salary


struct Employee highestSalaryEmployee = findHighestSalary(employeeDatabase, 5);
printf("Employee with the highest salary:\n");
printf("ID: %d, Name: %s, Salary: %.2f\n",
highestSalaryEmployee.employeeID, highestSalaryEmployee.name,
highestSalaryEmployee.salary);

// Calculate and display the average salary


float averageSalary = calculateAverageSalary(employeeDatabase, 5);
printf("Average Salary: %.2f\n", averageSalary);

// Display details of all employees


displayEmployeeDetails(employeeDatabase, 5);
return 0;
}
Output:
Employee with the highest salary:
ID: 103, Name: Bob Johnson, Salary: 75000.00
Average Salary: 62000.00
Employee Details:
ID: 101, Name: John Doe, Salary: 50000.00
ID: 102, Name: Jane Smith, Salary: 60000.00
ID: 103, Name: Bob Johnson, Salary: 75000.00
ID: 104, Name: Alice Williams, Salary: 55000.00
ID: 105, Name: Charlie Brown, Salary: 70000.00
7.Describe the concept of file management in C programming and Highlight the
significance of file handling for efficient data storage and Retrieval. Provide a
summary of common file operations and emphasize The essential functions
involved in file management.
Concept of File Management in C Programming:
File management in C programming involves handling files, which are used For storing
and retrieving data on secondary storage devices like hard drives,SSDs, or other storage
media. Files provide a way to store data persistently,And file management in C is
crucial for various applications, including data Storage, retrieval, and manipulation.
Significance of File Handling:
File handling is significant for several reasons:
• Persistent Storage: Files provide a means for storing data Persistently on disk or
other storage devices. This allows data to be Saved between program executions.
• Data Sharing: Files enable the sharing of data between different Programs or
even different instances of the same program. Data can Be written to a file by one
program and read by another.
• Data Organization: Files help in organizing data in a structured manner.
Different types of data can be stored in different files,making it easier to manage
and retrieve specific information.
• Data Backup: By writing data to files, applications can create backup copies,
helping prevent data loss in case of unexpected program termination or system
failures.
• Data Retrieval: Files allow for the retrieval of data stored earlier.
This is particularly important for applications that need to read and process previously
stored information.
Overview of File Operations in C:
File operations in C involve opening, closing, reading, and writing to files.
The key file operations include:
Opening a File:
The fopen function is used to open a file. It returns a file pointer that is used in
subsequent file operations.
FILE *fptr;
fptr = fopen("example.txt", "w"); // Opens a file for writing
Closing a File:
The fclose function is used to close a file once operations are complete.
fclose(fptr);
Reading from a File:
The fscanf or fgets functions are used to read data from a file.
fscanf(fptr, "%d", &variable); // Reads an integer from the
file Writing to a File:
The fprintf or fputs functions are used to write data to a file.
fprintf(fptr, "Hello, File!"); // Writes a string to the file
File Positioning:
The fseek and rewind functions are used to set the file position indicator to a specific
location within the file.
fseek(fptr, 0, SEEK_SET); // Sets the file position to the beginning
Checking End-of-File:
The feof function is used to check if the end of the file has been reached.
if (feof(fptr))
{
// End of file reached
}
Key Functions Involved in File Management: fopen:
Opens a file and returns a file pointer.
FILE *fopen(const char *filename, const char
*mode);
fclose: Closes a file.
int fclose(FILE *stream);
fread and fwrite:
Reads and writes blocks of data from/to a file.
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t count, FILE
*stream);
fscanf and fprintf:
Reads and writes formatted data to a file
int fscanf(FILE *stream, const char *format,
…);
int fprintf(FILE *stream, const char *format, …);
Fgets and fputs:
Reads and writes strings to a file.
char *fgets(char *str, int n, FILE *stream);
int fputs(const char *str, FILE *stream);
Fseek and rewind:
Sets the file position indicator to a specific location.
int fseek(FILE *stream, long int offset, int whence);
void rewind(FILE *stream);
These functions, along with others in the <stdio.h> library, enable Programmers to
perform various file operations in C programming. File Management is crucial for
handling data in a persistent and organized Manner in applications .

8.Examine the concept of buffering in file input/output operations in C


Programming. Discuss how buffering influences the efficiency and Performance of
file operations. Provide code examples to Demonstrate the impact of buffering on
reading and writing large Amounts of data to a file.

Buffering is a technique used to enhance the efficiency and performance of file


input/output operations. Buffering involves temporarily storing data in memory before it
is written to a file or read from a file. This process helps reduce the number of physical
read and write operations, improving overall performance.
How Buffering Works:
When you perform file operations like reading or writing, the data is not directly
transferred between the program and the file on disk. Instead, the C library uses an
intermediate buffer (an area in memory) to temporarily hold the data. This buffer is
managed by the Standard I/O library.
Impact of Buffering on Efficiency and Performance:
Reduced Disk Access: Buffering reduces the number of direct disk access operations,
as data is read or written in larger chunks rather than individual bytes or small chunks.
This minimizes the overhead associated with frequent disk access.
Batch Processing: Buffering allows the C library to batch multiple read or write
operations into a single disk operation. This batching reduces the overhead of system
calls and improves efficiency.
Optimized Disk I/O: Larger transfers between memory and disk are generally more
efficient than smaller transfers. Buffering allows the C library to optimize the size of
data transfers for better performance.
Code Examples:
Let's examine the impact of buffering on reading and writing large amounts of data to a
file using two scenarios: one with buffering and another without.

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.

You might also like