0% found this document useful (0 votes)
4 views12 pages

Module 5

The document contains multiple C programs demonstrating the use of structures and unions for various applications, such as finding the largest of three numbers, maintaining student records, and computing average marks. It also explains the differences between arrays and structures, memory allocation in structures versus unions, and the use of typedef for improved readability. Additionally, it illustrates how to implement nested structures and unions for efficient data management.

Uploaded by

crazysonu777togo
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)
4 views12 pages

Module 5

The document contains multiple C programs demonstrating the use of structures and unions for various applications, such as finding the largest of three numbers, maintaining student records, and computing average marks. It also explains the differences between arrays and structures, memory allocation in structures versus unions, and the use of typedef for improved readability. Additionally, it illustrates how to implement nested structures and unions for efficient data management.

Uploaded by

crazysonu777togo
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

Develop a C program using structures to find the Develop a C program to read and display

largest of three numbers. student information using a union.


#include <stdio.h> #include <stdio.h>
struct Numbers {
int a, b, c; union student
}; {
int main() { int roll_no;
struct Numbers n; char name[30];
printf(“Enter 3 numbers”); float marks;
scanf("%d %d %d", &n.a, &n.b, &n.c); };
int largest = n.a;
if (n.b > largest) largest = n.b; int main()
if (n.c > largest) largest = n.c; {
printf("Largest number = %d", largest); union student s;
return 0; printf("Enter Roll Number: ");
} scanf("%d", &s.roll_no);
printf("Roll Number = %d\n\n",
s.roll_no);
printf("Enter Name: ");
scanf(" %s", [Link]);
printf("Name = %s\n\n", [Link]);
printf("Enter Marks: ");
scanf("%f", &[Link]);
printf("Marks = %f\n", [Link]);
return 0;
}

Develop a C program to maintain a record of “N” Develop a C program to pass the entire
student details using an array of structures with four structure as a function argument.
fields (roll no, name, marks, and grade). Assume an #include <stdio.h>
appropriate data type for each field. Print the marks of struct student
the student, given the student’s name as input. {
#include <stdio.h> int roll_no;
#include <string.h> char name[30];
struct student float marks;
{ };
int roll_no; void display(struct student s)
char name[50]; {
float marks; printf("Student Details:");
char grade; printf("Roll No : %d", s.roll_no);
}; printf("Name : %s", [Link]);
int main() printf("Marks : %f", [Link]);
{ }
int n, i; int main()
char search_name[50]; {
struct student s[100]; struct student s1;
printf("Enter Roll Number: ");
printf("Enter number of students: "); scanf("%d", &s1.roll_no);
scanf("%d", &n); printf("Enter Name: ");
for (i = 1; i <= n; i++) scanf(" %s", [Link]);
{ printf("Enter Marks: ");
printf("\nEnter details of student %d\n", i ); scanf("%f", &[Link]);
printf("Roll No: "); display(s1);
scanf("%d", &s[i].roll_no); return 0;}

1
printf("Name: ");
scanf(" %s", s[i].name); // reads string with
spaces
printf("Marks: ");
scanf("%f", &s[i].marks);
printf("Grade: ");
scanf(" %c", &s[i].grade);
}
printf("\nEnter student name to search marks: ");
scanf(" %s", search_name);
for (i = 0; i < n; i++)
{
if (strcmp(s[i].name, search_name) == 0)
{
printf("Marks of %s = %f", s[i].name, s[i].marks);
return 0;
}
}
printf("Student not found.");
return 0;
}

Develop a C program using structure to read, write, and Illustrate three ways of accessing
compute average marks and display the students scoring of structure members in a
above and below the average marks for a class of N function with an example.
students.
#include <stdio.h> Three Ways of Accessing Structure
struct Student { Members in a Function
char name[30]; 1. Passing individual structure
float marks; members
}; 2. Passing entire structure (call by
int main() { value)
int n; 3. Passing pointer to structure (call by
float sum = 0, avg; reference)
scanf("%d", &n); #include <stdio.h>
struct Student s[n];
for(int i=1;i<=n;i++) { /* Structure definition */
scanf("%s %f", s[i].name, &s[i].marks); struct student
sum += s[i].marks; {
} int roll_no;
avg = sum / n; char name[30];
printf("Average = %f\n", avg); float marks;
printf("Above Average:\n"); };
for(int i=1;i<=n;i++)
if(s[i].marks > avg) /* 1. Passing individual members */
printf("%s\n", s[i].name); void display1(int r, char n[], float m)
printf("Below Average:\n"); {
for(int i=0;i<n;i++) printf("\nMethod 1: Individual
if(s[i].marks < avg) Members");
printf("%s\n", s[i].name); printf("\nRoll No: %d", r);
return 0; printf("\nName : %s", n);
} printf("\nMarks : %.2f\n", m);
}

2
/* 2. Passing entire structure */
void display2(struct student s)
{
printf("\nMethod 2: Entire Structure");
printf("\nRoll No: %d", s.roll_no);
printf("\nName : %s", [Link]);
printf("\nMarks : %.2f\n", [Link]);
}

/* 3. Passing pointer to structure */


void display3(struct student *s)
{
printf("\nMethod 3: Pointer to
Structure");
printf("\nRoll No: %d", s->roll_no);
printf("\nName : %s", s->name);
printf("\nMarks : %.2f\n", s->marks);
}

int main()
{
struct student s1 = {101, "Divya", 88.5};

/* Method 1 */
display1(s1.roll_no, [Link], [Link]);

/* Method 2 */
display2(s1);

/* Method 3 */
display3(&s1);

return 0;
}
Develop a C program to store and print the names, USNs, Develop a C program to read and display
subjects, and IA marks of students using structures. the information of n employees in a
#include <stdio.h> company using an array of structures.
struct student #include <stdio.h>
{ struct employee
char name[50]; {
char usn[20]; int emp_id;
char subject[30]; char name[30];
int ia_marks; char designation[20];
}; float salary;
int main() };
{ int main()
int n, i; {
struct student s[100]; struct employee e[100];
printf("Enter number of students: "); int n, i;
scanf("%d", &n);
for (i = 1; i < =n; i++) printf("Enter number of employees: ");
{ scanf("%d", &n);

3
printf("Enter details of student %d", i );
printf("Name: "); for (i = 1; i <= n; i++)
scanf(" %s", s[i].name); {
printf("USN: "); printf("\nEnter details of employee
scanf(" %s", s[i].usn); %d\n", i );
printf("Subject: ");
scanf(" %s", s[i].subject); printf("Employee ID: ");
printf("IA Marks: "); scanf("%d", &e[i].emp_id);
scanf("%d", &s[i].ia_marks);
} printf(" Student Details "); printf("Name: ");
for (i = 1; i <= n; i++) scanf(" %s", e[i].name);
{
printf("\nStudent %d", i ); printf("Designation: ");
printf("Name : %s", s[i].name); scanf(" %s", e[i].designation);
printf("USN : %s", s[i].usn);
printf("Subject : %s", s[i].subject); printf("Salary: ");
printf("IA Marks: %d\n", s[i].ia_marks); scanf("%f", &e[i].salary);
} }
return 0; printf(" Employee Details ");
} for (i = 0; i < n; i++)
{
printf("Employee %d", i );
printf("ID : %d", e[i].emp_id);
printf("Name: %s", e[i].name);
printf("Designation : %s", e[i].designation);
printf("Salary: %f", e[i].salary);
}
return 0;
}
Develop a C program to add two distances in feet and Distinguish between arrays and
inches using a structure. structures in C with an example.
#include <stdio.h> Feature Array Structure
struct distance
Collection of Collection of
{
int feet;
elements of elements of
Definition
float inches; same data different data
}; type types
Data Type Homogeneous Heterogeneous
int main() Using dot (.)
{ Access Using index
operator
struct distance d1, d2, sum; Continuous Continuous
/* Input first distance */ Memory
memory of memory of
printf("Enter first distance:\n"); Allocation
same type different types
printf("Feet: ");
scanf("%d", &[Link]); Store multiple Store related
printf("Inches: "); Purpose values of information of
scanf("%f", &[Link]); same kind different types
Example List of marks Student record
/* Input second distance */ No special Uses struct
printf("\nEnter second distance:\n"); Keyword
keyword keyword
printf("Feet: ");
scanf("%d", &[Link]);
printf("Inches: ");

4
scanf("%f", &[Link]);

/* Add distances */
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];

/* Convert inches to feet if inches >= 12 */


if ([Link] >= 12)
{
[Link] += (int)([Link] / 12);
[Link] = (int)[Link] % 12;
}

/* Display result */
printf("Sum of distances = %d feet= %f inches\n",
[Link], [Link]);

return 0;
}
What is typedef?
typedef is used to create an alias (new name) for an Analyze how a nested structure models
existing data type. student records: define Marks (three
When used with structures, it simplifies structure usage. subjects) inside Student (RollNo, Name,
Without typedef (Normal structure) Marks, Total). Implement an array of 5
#include <stdio.h>
students, compute each Total, and
struct student
display RollNo–Name–Total in a proper
{
int roll_no; format.
char name[30]; #include <stdio.h>
float marks; struct Marks {
}; int sub1;
int main() int sub2;
{ int sub3;
struct student s1; };
s1.roll_no = 101; struct Student {
printf("Roll No = %d\n", s1.roll_no); int rollNo;
return 0; char name[30];
} struct Marks m; // Nested structure
Every time we must write struct student. int total;
With typedef (Using alias) };
#include <stdio.h> int main() {
typedef struct struct Student s[5];
{ int i;
int roll_no; for (i = 1; i <= 5; i++) {
char name[30]; printf("Enter details of Student %d\n", i);
float marks; printf("Roll No: ");
} Student; scanf("%d", &s[i].rollNo);
int main()
{ printf("Name: ");
Student s1; scanf("%s", s[i].name);
s1.roll_no = 101; printf("Marks in 3 subjects: ");
printf("Roll No = %d\n", s1.roll_no); scanf("%d %d %d", &s[i].m.sub1,
return 0; &s[i].m.sub2, &s[i].m.sub3);
s[i].total = s[i].m.sub1 + s[i].m.sub2 +

5
} s[i].m.sub3;
Now we can use Student directly like a normal data type. }

printf("RollNo Name Total Marks");


for (i = 1; i <= 5; i++) {
printf("%d %s %d ", s[i].rollNo,
s[i].name, s[i].total);
}

return 0;
}
Examine how using typedef with nested structures
improves readability and modularity: define Date Analyze how a union allocates memory
(day, month, year) and Student (rollNo, name, dob compared to a structure and how the
of type Date). Accept input and display the student's compiler decides its total size.
information including Date of Birth in dd-mm-yyyy C programming, structures and unions are
format. user-defined data types used to group
variables of different data types. Though
#include <stdio.h> their syntax appears similar, they differ
significantly in memory allocation and
typedef struct {
usage. Understanding how the compiler
int day; allocates memory and determines their size
int month; is essential for efficient program design.
int year;
} Date; 2. Memory Allocation in Structure
 Each member of a structure is
typedef struct { allocated separate memory
int rollNo;  All members can store values
char name[30]; simultaneously
Date dob; // Nested structure  Memory is allocated in a sequential
} Student; manner
 Padding may be added to satisfy
alignment requirements
int main() {
Example
Student s; struct Sample {
printf("Enter Roll Number: "); int a; // 4 bytes
scanf("%d", &[Link]); float b; // 4 bytes
printf("Enter Name: "); char c; // 1 byte
scanf("%s", [Link]); };
printf("Enter Date of Birth (dd mm Total size = 4 + 4 + 1 + padding = 12 bytes
yyyy):”);
scanf("%d %d %d", &[Link], 3. Memory Allocation in Union
&[Link], &[Link]);  All members share a single
printf("Student Information "); memory location
 Only one member is active at a
printf("Roll Number : %d\n", [Link]);
time
printf("Name : %s\n", [Link]);  Memory is allocated based on the
printf("Date of Birth: %d-%d-%d\n", largest member
[Link], [Link], [Link]);  Saves memory compared to
return 0; structures
} Example
union Sample {
int a; // 4 bytes

6
float b; // 4 bytes
char c; // 1 byte
};
Total size = 4 bytes

4. Compiler’s Role in Size Determination


For Structure:
1. Adds size of all members
2. Applies padding for alignment
3. Ensures final size is a multiple of
the largest data type
For Union:
1. Identifies the largest member
2. Allocates memory equal to that
member’s size
3. Applies alignment rules if required

5. Comparison Between Structure and


Union
Feature Structure Union
Separate
Memory Shared
memory for
allocation memory
each member
Members
All at once One at a time
active
Sum of all Size of
Total size members + largest
padding member
Memory
Lower Higher
efficiency
Memory-
Complex
Usage optimized
records
data

6. Applications
 Structures: Student records,
employee details, database records
 Unions: Embedded systems,
protocol handling, memory-
constrained applications

Analyze the usage of a union named Data that can Distinguish between Structure and
store an int, float, or a character array of size 20. Union in C.
Write a C program to:
i. Assign values to each member sequentially.
ii. Print the value of each member immediately Structure Union
Aspect
after its assignment. ( struct ) ( union)
Examine and explain how the union’s memory is Definition Collection of Collection of
shared among the members variables of variables
A union in C is a user-defined data type in which all different data that share
members share the same memory location. This types stored the same
means that at any given time, only one member together memory

7
can store a valid value. Unions are mainly used to Structure Union
Aspect
optimize memory usage when multiple data types (struct) (union)
are not required simultaneously. location
A single
2. Definition of Union Data Separate
memory
The union Data can store: Memory memory is
block is
 an integer allocation allocated for
shared by all
 a floating-point value each member
members
 a character array of size 20 Sum of sizes Size of the
union Data { Size of data
of all members largest
int i; type
(plus padding) member only
float f; All members Only one
char str[20]; Members can be member can
}; accessibility accessed at the be used at a
 Size of int → 4 bytes same time time
 Size of float → 4 bytes More
 Size of char[20] → 20 bytes Memory Less memory
memory
Total size of the union = 20 bytes (largest efficiency efficient
efficient
member) Only the last
All values are
assigned
C Program Data storage stored
value is
#include <stdio.h> simultaneously
stored
#include <string.h> Assigning
union Data { Overwriting No overwriting one member
int i; of data occurs overwrites
float f; others
char str[20];
Only one
}; Multiple
member can
Initialization members can
be initialized
int main() { be initialized
at a time
union Data d;
Records like Applications
d.i = 15;
student or requiring
printf("After assigning integer:"); Use cases
employee memory
printf("d.i = %d", d.i);
details optimization
d.f = 12.5;
Example struct union Data
printf("After assigning float:\n"); Student s; d;
usage
printf("d.f = %f", [Link]([Link], "Union
Example");
printf("After assigning string:\n");
printf("[Link] = %s", [Link]);
return 0;
}

4. Sample Output
After assigning integer:
d.i = 15

After assigning float:


d.f = 12.50

8
After assigning string:
[Link] = Union Example

5. Examination of Memory Sharing


Valid Effect on
Assigned
Step Data Other
Member
Stored Members
Float and
Integer
1 d.i = 15 string become
value
invalid
Float Integer value is
2 d.f = 12.5
value overwritten
[Link] = Integer and
String
3 "Union float become
value
Example" invalid
Only the most recently assigned member
contains valid data
Union ensures efficient memory utilization
Accessing any member other than the last assigned
one results in undefined or garbage values

Analyze how the use of sizeof() can help


Analyze how typedef creates aliases for simple data make programs portable across systems
types and complex structures in C, with syntax and with different data-type sizes.
examples.
In C, typedef is a keyword used to create an alias 1. Data type sizes vary: Different
(alternate name) for an existing data type. It does systems/compilers may assign
not create a new data type but provides a different sizes to basic data
meaningful name that improves readability, types. For example, int could be
modularity, and maintainability of programs. 2 bytes on one system and 4
bytes on another.
General Syntax 2. Problem in portability:
typedef existing_data_type new_type_name; Hardcoding sizes in programs
(like assuming int is always 4
1. typedef with Simple Data Types bytes) can lead to incorrect
typedef is used to simplify long or platform- memory allocation, data
dependent data types. corruption, or unexpected
Example: behavior on other systems.
typedef unsigned int UINT; 3. Role of sizeof(): The sizeof()
typedef float REAL; operator returns the actual size
Usage: (in bytes) of a data type or
UINT count = 10; variable on the current system.
REAL price = 45.5; 4. Dynamic memory allocation:
✔ Improves clarity and portability. Using sizeof() ensures correct
memory allocation.
2. typedef with Arrays 5. int *ptr = (int*) malloc(10 *
It helps in defining array types clearly and sizeof(int));
compactly. This works regardless of whether int is

9
Example: 2, 4, or 8 bytes.
typedef int Marks[5]; 6. Array and structure
Usage: portability: When dealing with
Marks m = {80, 75, 90, 85, 88}; arrays or structures, sizeof()
✔ Makes array declarations more readable. helps in copying, sending, or
3. typedef with Pointers saving data without assuming
Reduces confusion in pointer declarations. fixed sizes.
Example: struct Student s;
typedef int* IntPtr; fwrite(&s, sizeof(s), 1, file);
Usage: 7. Loop iterations based on size:
IntPtr p; It can calculate the number of
✔ Enhances readability and avoids declaration elements in an array safely:
errors. int arr[10];
int n = sizeof(arr)/sizeof(arr[0]);
4. typedef with Structures (Complex Data Types) // always 10
Removes repeated use of the struct keyword. 8. Safe pointer arithmetic:
Without typedef: Pointer offsets depend on the
struct Student { size of the data type. Using
int rollNo; sizeof() ensures correct memory
char name[30]; addressing across systems.
}; 9. Avoids platform-specific bugs:
struct Student s; Programs using sizeof()
With typedef: automatically adapt to the data
typedef struct { model of the target system,
int rollNo; reducing portability issues.
char name[30]; 10. Enhances code
} Student; maintainability: If data types
Usage: change, code using sizeof() does
Student s; not need modification for correct
✔ Makes code concise and modular. memory handling.
By dynamically determining the
5. typedef with Nested Structures size of data types at compile-
Supports hierarchical data modeling. time, sizeof() ensures that
typedef struct { programs are portable, safe, and
int day, month, year; reliable across different
} Date; hardware architectures.

typedef struct {
int rollNo;
char name[30];
Date dob;
} Student;

Examine the concept of bit-fields in C to create a Analyze how enumerations can be used
structure that stores the ON/OFF status (1 bit each) to represent constant values such as
of four electronic devices: TV, Fan, Light, and AC. days of the week or months of the year
Display their statuses using printf(). with its syntax and example

10
1. Concept of Enumeration (enum)
 An enumeration is a user-
Bit-field: A bit-field allows you to allocate a specific defined data type in C that
number of bits to a structure member instead of the assigns names to integral
default size of the data type. constants.
Purpose: Useful when you want to store multiple  Improves code readability by
Boolean (ON/OFF) flags or small integers efficiently replacing numeric constants
in memory. with meaningful names.
Syntax:  Syntax:
struct Device { enum EnumName {
unsigned int TV : 1; // 1 bit for TV status constant1,
unsigned int Fan : 1; // 1 bit for Fan status constant2,
unsigned int Light : 1; // 1 bit for Light status constant3,
unsigned int AC : 1; // 1 bit for AC status ...
}; };
Here, :1 indicates that each member uses only 1 bit.  By default, the first constant has
C Program Example the value 0, the next 1, and so on.
#include <stdio.h> You can also assign specific
struct Devices { integer values manually.
unsigned int TV : 1;
unsigned int Fan : 1; 2. Using enum for Days of the Week
unsigned int Light : 1; #include <stdio.h>
unsigned int AC : 1;
}; int main() {
int main() { // Define an enumeration for days
struct Devices d; enum Weekday { Sunday, Monday,
// Assigning ON(1)/OFF(0) status Tuesday, Wednesday, Thursday, Friday,
[Link] = 1; // TV is ON Saturday };
[Link] = 0; // Fan is OFF
[Link] = 1; // Light is ON enum Weekday today;
[Link] = 0; // AC is OFF
today = Wednesday; // Assign a day
// Display statuses
printf("TV: %s\n", [Link] ? "ON" : "OFF"); printf("Day number: %d\n",
printf("Fan: %s\n", [Link] ? "ON" : "OFF"); today); // Output: 3 (0-based index)
printf("Light: %s\n", [Link] ? "ON" : "OFF");
printf("AC: %s\n", [Link] ? "ON" : "OFF"); return 0;
return 0; }
} Explanation:
Output  Sunday is 0, Monday is 1, …,
TV: ON Wednesday is 3.
Fan: OFF  Using enums makes the program
Light: ON more readable than using plain
AC: OFF numbers.
Bit-fields save memory because each device uses
only 1 bit instead of an entire int (usually 4 bytes). 3. Using enum for Months of the Year
Accessing and assigning values is the same as #include <stdio.h>
normal structure members.
Bit-fields are ideal for storing flags, statuses, or int main() {

11
small ranges of values. enum Month { Jan=1, Feb, Mar, Apr,
May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };

enum Month m = Oct;

printf("Month number: %d\n",


m); // Output: 10

return 0;
}
Explanation:
 Assigning Jan=1 starts
enumeration from 1 instead of 0.
 Each subsequent month
increments automatically.

4. Key Advantages
1. Readability: Replaces numeric
constants with meaningful
names.
2. Maintainability: Easy to
add/remove constants without
changing other code.
3. Type Safety: Enums are treated
as a distinct type by the compiler.
4. Memory Efficient: Stored as
integers internally (usually 4
bytes).

12

You might also like