0% found this document useful (0 votes)
9 views15 pages

EST102: Programming in C: Structures and Unions

The document discusses structures in C programming. It defines structures as a user-defined data type that allows grouping of related data items under a single name. The document explains how to define structures, declare structure variables, access structure members, initialize structure members, operations on structures, arrays of structures and nested structures.

Uploaded by

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

EST102: Programming in C: Structures and Unions

The document discusses structures in C programming. It defines structures as a user-defined data type that allows grouping of related data items under a single name. The document explains how to define structures, declare structure variables, access structure members, initialize structure members, operations on structures, arrays of structures and nested structures.

Uploaded by

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

EST102 : Programming in C

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.

10.1.1 Defining a structure


A structure must be defined in terms of its individual members. In general terms, a structure
may be defined as:
struct tag
{
member-1;

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;

10.2 Accessing structure elements


Individual members of a structure are accessed through the use of the dot (·) operator. For
example, to print the edition of book b1, we write
printf("%d",b1.edition);
Similarly to input the title of book b3, you write:
gets(b3.title);
or
scanf("%s",b3.title);

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

10.3 Initializing structure members


The members of a structure variable can be assigned initial values in much the same manner
as the elements of an array. The initial values must appear in the order in which they will
be assigned to their corresponding structure members, enclosed in braces and separated by
commas.

Example 10.6. This example illustrates how a structure variable is initialized.


struct book
{
char title[15];
float price;
int edition;
};
struct book b={"C Programming", 175.00, 2};
This statement assigns “C Programming” to title, 175.00 to price and 2 to edition. ■

It is also possible to initialize the structure variable in the structure definition.

Example 10.7. This is another way to initialize structure variables.


struct book
{
char title[15];
float price;
int edition;
}b={"C Programming", 175.00, 2};

There are few rules to keep in mind while initializing structure variables in the program.

1. You cannot initialize individual members inside the structure template.

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.

4. The uninitialized members will be assigned default values as follows:

• Zero for integer and floating point numbers


• ‘\0’ for characters and strings

For example, with the book structure, if you write

struct book b={"C Programming", 175.00};

then edition will be assigned 0.

10.4 Operations on structure members and on


structure variables
The individual members in a structure can be manipulated using any operation. Following
are some examples:

⇒ 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.

Example 10.8. This program illustrates structure assignments


struct sample
{
int a, b;
} x, y;
x.a = 10;
x.b = 20;
y = x;
printf("%d %d", y.a, y.b);

This will print 10 20 ■

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;

10.5 Array of structures


Just as you have array of integers or of characters, you can also define an array of structure
variables. Such an array is called array of structures – an array in which each element is
a structure variable. For example, if you want to have five variables of the book type, you
can declare thus:
struct book b[5];
Here b[0] will pertain to the zeroth book, b[1] to the first book and so on. To access the
title of second book, you just write b[2].title.
Example 10.9. This program inputs and displays the details of several books.
#include<stdio.h>
struct book
{
char title[15];
char author[15];
int edition;
float price;
};
main()
{
struct book b[10];
int i,n;
printf("Enter how many books you want to process\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the title of book %d \n",i+1);
scanf(" %s",b[i].title);
printf("Enter the author of book %d \n",i+1);
scanf(" %s",b[i].author);
printf("Enter the edition of book %d \n",i+1);
scanf("%d",&b[i].edition);
150 CHAPTER 10. STRUCTURES AND UNIONS

printf("Enter the price of book %d \n",i+1);


scanf("%f",&b[i].price);
}
for(i=0;i<n;i++)
{
printf("BOOK %d DETAILS\n",i+1);
printf("Title : %s\n",b[i].title);
printf("Author : %s\n",b[i].author);
printf("Edition : %d\n",b[i].edition);
printf("Price : %f\n",b[i].price);
}
}

10.6 Nested structures


Suppose we have a structure named employee with the following template:
struct employee
{
char empName[15];
int empID;
char houseName[15];
char streetName[15];
char cityName[15];
int pinCode;
char state[15];
int salary;
};
Here the members houseName to state collectively represent the address of the employee.
Thus they could conveniently be combined to form another structure address as follows:
struct employee
{
char empName[15];
int empID;
struct address
{
char houseName[15];
char streetName[15];
char cityName[15];
int pinCode;
char state[15];
}addr;
int salary;
10.7. STRUCTURES AND FUNCTIONS 151

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

10.7 Structures and functions


There are two different ways to pass structure-type information to a function. Structure
members can be transferred individually, or entire structures can be transferred. Individual
structure members can be passed to a function as arguments in the function call. To do so,
each structure member is treated the same as an ordinary variable. A more efficient way
is to pass an entire structure to a function. This is achieved by passing structure variable
as argument to the concerned function. While declaring such functions, the argument type
should be specified as the structure type.

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.

Example 10.11. Consider the definition


union result
{
char grade;
int marks;
}cp;
Here you have a union variable, cp, of type result. It can have one active member at a
time: either a character(grade) or an integer quantity (marks). ■

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.

10.9 Programming examples


Program 10.77. Input the details (name, roll number and marks in 6 subjects) of n
students. Determine the rank list of the students based on total marks and print the
student details in the increasing order of ranks.
#include<stdio.h>
typedef struct
154 CHAPTER 10. STRUCTURES AND UNIONS

{
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:

1. Storage – whether the variable will be stored in memory or in registers.

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.

There are four storage classes:

1. Automatic

2. Register

3. Static

4. Global or external

158

You might also like