EST102: Programming in C: Structures and Unions
EST102: Programming in C: Structures and Unions
Chapter 10
Structures and Unions
Narasimhan T.
10.1 Structure
Suppose you want to store the details of a book. You may have to store details like title,
price and edition. What is the big deal? You just define three variables viz. title, price
and edition. This seems perfectly fine until you think more on it. The three pieces of
information: title, price and edition are related in the sense that they all pertain to a single
book. But the corresponding variables are unrelated: they are just three separate entities.
To bridge this gap, you need a technique to relate the three variables or wrap them into a
single unit.
You cannot use an array in the above situation as the three variables are of different types.
You need a more powerful user defined data type in which the individual elements can
differ in type. To solve this problem, C provides a special data type – the structure. A
structure is a collection of one or more variables (elements), possibly of different types,
grouped together under a single name for convenient handling. The individual structure
elements are referred to as members or fields. Structures help to organize complicated
data, particularly in large programs, because they permit a group of related variables to be
treated as a single unit instead of as separate entities.
144
10.1. STRUCTURE 145
member-2;
.
.
member-m;
};
Here, struct is a required keyword; tag is a name that identifies the structure; and
member-1, member-2,· · · · · · , member-m are the member declarations. Notice that the def-
inition is terminated by a semicolon. This is because a structure definition is a statement.
The above definition is also called a structure declaration or a structure template.
Example 10.1. For the book scenario discussed earlier, we could define a structure like
this
struct book
{
char title[15];
float price;
int edition;
};
■
Once the new structure data type has been defined, one or more variables of that type
can be declared. This is done as follows:
struct tag variable-1 , variable-2, . . . , variable-n;
where struct is a required keyword, tag is the name that appeared in the structure decla-
ration and variable-1 , variable-2, . . . , variable-n are structure variables of
type tag.
Example 10.2. This example declares three variables b1, b2, b3 of the type book.
struct book b1, b2, b3 ;
■
To avoid the use of the keyword struct in variable declarations, we can use typedef as
illustrated below.
Example 10.3. This is another way to declare structure variables.
typedef struct
{
char title[15];
float price;
int edition;
}book;
book b1,b2;
146 CHAPTER 10. STRUCTURES AND UNIONS
It is also possible to combine the structure definition and structure variable declaration
in one statement.
Example 10.4. This is yet another way to declare structure variables.
struct book
{
char title[15];
float price;
int edition;
}b1,b2,b3;
Example 10.5. This program inputs and displays the details of a book.
#include<stdio.h>
struct book
{
char title[15];
char author[15];
int edition;
float price;
};
main()
{
struct book b;
printf("Enter the title of the book\n");
gets(b.title);
printf("Enter the author of the book\n");
gets(b.author);
printf("Enter the price of the book\n");
scanf("%f",&b.price);
printf("Enter the edition of the book\n");
10.3. INITIALIZING STRUCTURE MEMBERS 147
scanf("%d",&b.edition);
printf("BOOK DETAILS\n");
printf("Title : %s\n",b.title);
printf("Author : %s\n",b.author);
printf("Edition : %d\n",b.edition);
printf("Price : %f\n",b.price);
}
There are few rules to keep in mind while initializing structure variables in the program.
2. The order of values enclosed in braces must match the order of members in the
structure definition.
148 CHAPTER 10. STRUCTURES AND UNIONS
3. It is possible to initialize only the first few members and leave the remaining unini-
tialized. The uninitialized members should be only at the end of the list.
⇒ if(b.price>100)
b.price-=10;
⇒ b.price++
The precedence of the member operator ('.') is higher than all arithmetic and relational
operators. So there is no need to put parenthesis like (b.price)++
You can assign one structure variable to another variable of same structure. You need
not assign the value of each member separately.
Comparison of two structure variables is not permitted. Following statements will result
in errors.
10.5. ARRAY OF STRUCTURES 149
– if(b1==b2)
– if(b1!=b2)
However you can compare two structure members like
⇒ if(b1.price>b2.price)
b1.price-=50;
};
The above template can also be written as:
struct address
{
char houseName[15];
char streetName[15];
char cityName[15];
int pinCode;
char state[15];
};
struct employee
{
char empName[15];
int empID;
struct address addr;
int salary;
};
To access the houseName we write
emp.addr.houseName
where emp is the variable of type struct employee. It is also possible to nest more than
one structure inside another structure.
Example 10.10. The following program defines a structure dob to store the date of birth
of a person. Also a function findYounger() is defined to determine the younger of two
persons Alice and Bob by inputting their dates of birth. The two structure variables repre-
senting the two dates of birth are passed as arguments to this function.
#include<stdio.h>
typedef struct
{
int day, month, year;
152 CHAPTER 10. STRUCTURES AND UNIONS
}dob;
void findYounger(dob, dob);
main()
{
dob a,b;
printf("Enter the DOB of Alice (in the order day, month (1 to 12) and
year)\n");
scanf("%d %d %d",&a.day, &a.month, &a.year);
printf("Enter the DOB of Bob (in the order day, month (1 to 12) and
year)\n");
scanf("%d %d %d",&b.day, &b.month, &b.year);
findYounger(a,b);
}
void findYounger(dob a, dob b)
{
if(a.year>b.year)
printf("Alice is younger");
else if(a.year==b.year&&a.month>b.month)
printf("Alice is younger");
else if(a.month==b.month&&a.day>b.day)
printf("Alice is younger");
else
printf("Bob is younger");
}
A function can return a structure variable as well. For this, you just specify the return
type of the function as the structure type. See Program 10.78.
10.8 Union
Just like structures, unions can also be used to group together heterogeneous data (data
with different types). However, the similarity ends here. With a structure, each individual
member is assigned its own storage area within the computer’s memory wheras all the
members of a union share the same storage area. Thus, unions are used to conserve memory.
They are useful for applications involving multiple members, where values need not be
assigned to all of the members simultaneously. Declaring a union is similar to declaring a
structure. Its general form is:
union tag
{
member-1;
member-2;
.
.
10.9. PROGRAMMING EXAMPLES 153
member-m;
};
where union is a required keyword and the other terms have the same meaning as in a
structure definition. Once a union is defined, union variables can then be declared as:
union tag variable-1 , variable-2, . . . , variable-n;
where union is a required keyword, tag is the name that appeared in the union definition
and variable-1 , variable-2, . . . , variable-n are variables of type tag.
To access a union member, you use the same syntax as that you did for structure
members. For example, with the union definition as above, you could write
cp.grade='S';
However, since all the union members share the same location, only one member can be
accessed at a time. Thus, while accessing an union member, you should make sure that you
are accessing the member whose value is currently stored. For example, the code
cp.grade='S';
cp.marks=92;
printf("You have obtained %c grade for end semester examination in
Computer Programming",cp.grade);
could yield unexpected results. This is because you can store only one value, either grade
or marks in the allocated space. Thus when you store grade and later try to store marks,
it will overwrite grade.
{
char name[15];
int roll, marks[6], total;
}student;
main()
{
student s[10],temp; // You assume n is less than or equal to 10
int n,i,j;
printf("How many students?");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter student name\n");
scanf("%s",s[i].name);
printf("Enter roll number\n");
scanf("%d",&s[i].roll);
printf("Enter marks in six subjects\n");
s[i].total=0;
for(j=0;j<6;j++)
{
scanf("%d",&s[i].marks[j]);
s[i].total+=s[i].marks[j];
}
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(s[j].total<s[j+1].total)
{
temp=s[j];
s[j]=s[j+1];
s[j+1]=temp;
}
}
}
for(i=0;i<n;i++)
{
printf("DETAILS OF STUDENT WITH RANK %d \n",i+1);
printf("Name:%s\n",s[i].name);
printf("Roll:%d\n",s[i].roll);
for(j=0;j<6;j++)
printf("Mark %d: %d\n",j+1,s[i].marks[j]);
printf("Total:%d\n",s[i].total);
}
10.9. PROGRAMMING EXAMPLES 155
Program 10.78. Input the details (name, employee ID and date of joining) of two
employees (using structure). Represent the date of joining as a nested structure. Print
the details of the employee with more experience than the other in the company. Define a
function findSenior() for this. The function should return a variable of employee structure
type. Assume the two employees have joined in different years.
#include<stdio.h>
typedef struct
{
int date;
char month[15];
int year;
}doj;
typedef struct
{
char name[15];
int empID;
doj d;
}employee;
employee findSenior(employee[]);
main()
{
employee e[2],senior;
int i;
for(i=0;i<2;i++)
{
printf("Enter employee name\n");
scanf("%s",e[i].name);
printf("Enter employee ID\n");
scanf(" %d",&e[i].empID);
printf("Enter day of joining\n");
scanf("%d",&e[i].d.date);
printf("Enter month of joining\n");
scanf("%s",e[i].d.month);
printf("Enter year of joining\n");
scanf(" %d",&e[i].d.year);
}
senior=findSenior(e);
printf("DETAILS OF THE SENIOR EMPLOYEE\n");
printf("Name:%s\n",senior.name);
printf("Employee ID:%d\n",senior.empID);
printf("Date of joining:%d %s
156 CHAPTER 10. STRUCTURES AND UNIONS
%d\n",senior.d.date,senior.d.month,senior.d.year);
}
employee findSenior(employee e[])
{
employee s;
if(e[0].d.year<e[1].d.year)
s=e[0];
else
s=e[1];
return s;
}
Program 10.79. In a company there are two type of employees – Type0 and Type1.
Employees belonging to Type0 are paid on hourly basis at the rate of | 750 per hour. Type1
employees are paid monthly, and their gross salary is calculated as the sum of basic pay,
DA (125% of basic pay) and HRA (| 550). Input the number of hours for Type0 employees
and basic pay of Type1 employees and print the gross salary.
#include<stdio.h>
typedef union
{
int hours;
float basicpay;
}salary;
typedef struct
{
char name[15],dept[15];
int type;
float gross;
salary s;
}employee;
main()
{
employee emp;
printf("Enter the name of employee");
scanf("%s",emp.name);
printf("Enter the department of employee");
scanf("%s",emp.dept);
printf("Enter the type of employee:0 or 1\n");
scanf("%d",&emp.type);
if(emp.type==0)
{
printf("Enter the number of hours\n");
scanf("%d",&emp.s.hours);
emp.gross=emp.s.hours*750;
10.9. PROGRAMMING EXAMPLES 157
}
else
{
printf("Enter the basic pay\n");
scanf("%f",&emp.s.basicpay);
emp.gross=emp.s.basicpay+emp.s.basicpay*1.25+550;
}
printf("Employee Details\n");
printf("Name:%s\n",emp.name);
printf("Department:%s\n",emp.dept);
printf("Salary:%f\n",emp.gross);
}
EST102 : Programming in C
Chapter 11
Storage classes
Narasimhan T.
11.1 Introduction
To fully define a variable you need to mention not only its data type but also its ‘storage
class’. A variable’s storage class gives the following pieces of information:
2. Default initial value – what will be the initial value of the variable, if initial value is
not specifically assigned.
3. Scope – over what regions of the program, the variable’s value can be accessed. The
scope denotes the active regions of the variable.
4. Lifetime – period of time during which a variable retains its value during the program
execution. Lifetime (also called longevity) denotes the alive period of the variable.
1. Automatic
2. Register
3. Static
4. Global or external
158