Lab 9
Computer Programming
ECO 123
1/4/2022 1
Lab 9
Lab objectives
1. Difference between structures & unions
2. Structures declaration
3. Structures examples • Structures
1/4/2022 2
structures in C
A structure is a user-defined data type available
in C that allows to combining data items of
different kinds. Structures are used to represent a
record.
1/4/2022 3
Defining a structure: To define a structure, you must use the
struct statement. The struct statement defines a new data type,
with more than or equal to one member. The format of the struct
statement is as follows:
struct [structure name]
{
member definition;
member definition;
...
member definition;
};
1/4/2022 4
Union
A union is a special data type available in C that allows
storing different data types in the same memory
location. You can define a union with many members,
but only one member can contain a value at any given
time. Unions provide an efficient way of using the
same memory location for multiple purposes.
1/4/2022 5
Defining a Union: To define a union, you must use the union
statement in the same way as you did while defining a
structure. The union statement defines a new data type with
more than one member for your program. The format of the
union statement is as follows:
union [union name]
{
member definition;
member definition;
...
member definition;
};
1/4/2022 6
Ex1: C program to create, declare and initialize structure
In this program, we will learn how to declare a structure
with different types of variables, declare and
initialization of structure variable? Here we are not
reading values from keyboard; we are assigning the
values to the structure members at the time of structure
variable declaration.
1/4/2022 7
1/4/2022 8
Ex2: Write C program to accept the details of
employee and display them using structure.
Details consist of Employee ID, Name,
Designation, Department, Salary.
1/4/2022 9
1/4/2022 10
1/4/2022 11
Ex3: C program to read information of
student. It contains Name, Roll number,
Birthday, admission date. Calculate age of
student at the time of admission.
1/4/2022 12
1/4/2022 13
1/4/2022 14
Ex4: Write a 'C' Program to create a structure
of student having fields roll_no, stud_name,
mark1, mark2, mark3. Calculate total marks
and average marks. Arrange the records in
descending order of marks.
1/4/2022 15
1/4/2022 16
1/4/2022 17
1/4/2022 18