1. 1
INDEX
Unit -5 CONTENT PAGE NO
Introduction 2
need for structure data type 3
structure definition 2
Structure declaration 2
Structure within a structure 11
Union 16
Programs using structures
and Unions
20
Storage classes 20
Pre-processor directives 25
2. 2
UNIT V STRUCTURES AND UNIONS 9
Introduction – need for structure data type – structure definition – Structure declaration – Structure
within a structure - Union - Programs using structures and Unions – Storage classes, Pre-process or
directives.
UNIT V
STRUCTURES AND UNIONS
Structure
In C programming , the various data types are
• Simple Data type
Integer, Real, Void, Char
• Structured Data type
Array, Strings
• User Defined Data type
Structures, Unions ,Enum
A structure is a user defined data type which allows you to combine data items of
different kinds into a single unit. All the elements of a structure are stored at contiguous
memory locations. i.e., store heterogeneous data under unique name.
Keyword 'struct' is used to declare structure. The variables which are declared inside
the structure are called as 'members of structure'.
Member of the structure variables can be initialized. The initialization for each
variable must be enclosed in braces. Note that there is a semicolon after the closing curly
brace.
Syntax:
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
3. 3
- - - - - - - - - - -
<data-type> element n;
}struct_var;
Example :
struct emp_info
{
char emp_id[10];
char nm[100];
float sal;
}emp;
Note :
1. Structure is always terminated with semicolon (;).
2. Structure name as emp_info can be later used to declare structure variables of its
type in a program.
Need for a structures
Structures makes a program to be modular program.
- Easier to modify.
Structure are used for whenever a lot of data needs to be grouped together—address book.
INSTANCES OF STRUCTURE :
Instances of structure can be created in two ways as,
Instance 1:
4. 4
struct emp_info
{
char emp_id[10];
char nm[100];
float sal;
}emp;
Instance 2:
The syntax of declaring a structure is
struct <struct_name> <variable_name>;
struct emp_info
{
char emp_id[10];
char nm[100];
float sal;
};
struct emp_info emp;
In above example, emp_info is a simple structure which consists of stucture members as
Employee ID(emp_id), Employee Name(nm), Employee Salary(sal).
ACEESSING STRUCTURE MEMBERS :
The structure members cannot be directly accessed. Structure members can be
accessed using member access operator ('.') . It is also called as 'dot operator' or 'period
operator'.
The syntax : the name of structure variable followed by a dot and then the name of
member variable.
5. 5
structure_var . member var;
To display a single person as a employee, the following program explains
/* details of an employee */
#include <stdio.h>
#include <conio.h>
struct emprec
{
char ename[100];
char eaddr[100];
}emp;
void main()
{
clrscr();
printf("n Enter employee Name : ");
gets(emp.ename);
printf("n Enter Address : ");
gets(emp.eaddr);
printf("nn employee Name : %s",emp.ename);
printf("nn Address : %s",emp.eaddr);
getch();
}
output
Enter employee Name : Saravanan
Enter Address : Madurai
6. 6
Enter employee Name : Pandiarajan
Address : Madurai
Ex: Similarly a student record
/* to store information of single record */
#include <stdio.h>
struct student{
char name[50];
int rollno;
float marks;
};
int main(){
struct student s;
printf("Enter student record:nn");
printf("Enter name: ");
scanf("%s",s.name);
printf("Enter roll number: ");
scanf("%d",&s.rollno);
printf("Enter marks: ");
scanf("%f",&s.marks);
printf("n printing n");
printf("Name: %sn",s.name);
printf("Roll: %dn",s.rollno);
printf("Marks: %.2fn",s.marks);
return 0;
}
output
7. 7
Enter student record :
Enter name : Saravanan
Enter roll number : 104
Enter marks : 87
Printing
Name : Saravanan
Roll no: 104
Marks : 87
ARRAY OF STRUCTURES:
The array of structure is used to store the large number of similar records. For
example to store the record of 10 employees then array of structure is used.
Defining array of structure:
The method to define and access array of structure is similar to array.
The syntax to define the array of structure is
Struct <struct_name> <var_name> <array_name> [<indexvalue>];
Example:-
Struct student stu[10];
Example:
/* to display 5 subjects of a student */
#include <stdio.h>
#include <conio.h>
8. 8
struct student
{
int rno, mrks[5];
char name;
}stu;
void main()
{
int i,total;
clrscr();
total = 0;
printf("nt Enter Roll Number : ");
scanf("%d",&stu.rno);
printf("nt Enter Marks of 3 Subjects : ");
for(i=0;i<3;i++)
{
scanf("%d",&stu.mrks[i]);
total = total + stu.mrks[i];
}
printf("nnt Roll Number : %d",stu.rno);
printf("nnt Marks are :");
for(i=0;i<3;i++)
{
printf(" %d",stu.mrks[i]);
}
printf("nnt Total is : %d",total);
getch();
}
Output
Enter Roll Number : 1
9. 9
Enter Marks of 3 Subjects : 63 66 68
Roll Number : 1
Marks are : 63 66 68
Total is : 197
In this program, a structure(student) is created which contains roll no and
marks as its data member. Then, a structure variable(stu) is created. Then, data ( roll
no and marks) is taken from user and stored in data members of structure variable stu.
Using this stu variable, the data to be displayed in the screen.
Similarly we print n students mark statement as array of structure.
/* To print students mark statement*/
#include"stdio.h"
#include"conio.h"
struct student
{
char name[25],grade;
int reg_no[15];
int s1,s2,s3,s4,s5,total;
float avg;
}st[10];
void main()
{
int i,n,total;
float avg;
printf("n Enter the no of Students:");
scanf("%d",&n);
printf("n Enter the name, regno and 5 subject marks:");
10. 10
for(i=0;i<n;i++)
{
printf("n Enter the name, regno and 5 sub marks”,%d",i+1);
scanf("%s%d%d%d%d%d%d", &st[i].name, &st[i].reg_no, &st[i].s1, &st[i].s2, &st[i].s3,
&st[i].s4, &st[i].s5);
st[i].total=st[i].s1+st[i].s2+st[i].s3+st[i].s4+st[i].s5;
st[i].avg=st[i].total/5;
if((st[i].s1<50)||(st[i].s2<50)||(st[i].s3<50)||(st[i].s4<50)||(st[i].s5<50))
{
st[i].grade='U';
printf("Ur grade is %c", st[i].grade);
}
else
{
st[i].grade='P';
printf("Ur grade is %c", sa[i].grade);
}
}
}
In this program, a structure(student) is created which contains name,regno and
5 marks as its data member. Then, a structure variable(st) is created. Then, data
name, regno and 5 marks of 10 students is taken from user and stored in data
members of structure variable st.
Using this stu variable, the data to be displayed in the screen.
Output:
Enter the no of Students: 2
Enter the name, regno and 5 subject marks:
100
11. 11
Deepa
50
50
50
50
50
Ur grade is P
Enter the name, regno and 5 subject marks:
101
Sasi
34
50
50
50
50
Ur grade is: U
STRUCTURES WITHIN STRUCTURES (NESTED STRUCTURES) :
Structures can be used as structures within structures. It is also called as 'nesting of
structures'.
Defining structures within structures:
Define a variable of structure type as a member of other structure type.
The syntax to define the structure within structure is
struct structure_nm
{
<data-type> element 1;
12. 12
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
struct structure_nm1
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
}inner_struct_var;
}outer_struct_var;
This tag explains nested structures.
struct stud_Res
{
int rno;
char nm[50];
char std[10];
struct stud_subj
{
char subjnm[30];
int marks;
}subj;
}result;
Accessing structures within structures
13. 13
Accessing inner structures within outer structure is accessed by using two period (.) symbol
The syntax to access the structure within structure is
struct _var. nested_struct_var. struct_member;
Example :
Emp.address.city;
/* to display marks structure with in student structure */
#include <stdio.h>
#include <conio.h>
struct stud_Res
{
int rno;
char std[10];
struct stud_Marks
{
char subj_nm[30];
int subj_mark;
}marks;
}result;
void main()
{
clrscr();
printf("nt Enter Roll Number : ");
scanf("%d",&result.rno);
printf("nt Enter Standard : ");
14. 14
scanf("%s",result.std);
printf("nt Enter Subject Code : ");
scanf("%s",result.marks.subj_nm);
printf("nt Enter Marks : ");
scanf("%d",&result.marks.subj_mark);
printf("nnt Roll Number : %d",result.rno);
printf("nnt Standard : %s",result.std);
printf("nSubject Code : %s",result.marks.subj_nm);
printf("nnt Marks : %d",result.marks.subj_mark);
getch();
}
Output
Enter Roll Number : 1
Enter Standard : MCA(Sci)-I
Enter Subject Code : SUB001
Enter Marks : 63
Roll Number : 1
Standard : MCA(Sci)-I
Subject Code : SUB001
Marks : 63
Pointers & Structures
We can also define a pointer variable of structure type. The syntax to define the
pointer to structure as same as pointer type.
struct <struct_name> *<pointer_var_name>;
Example:
15. 15
struct student *stu;
stu – pointer variable of student structure.
Access the Pointer - Structures
It is accessed by using the pointer variable followed with arrow operator() .
The syntax to access the pointer - structure.
pointer_var structure_member;
Example:
stuname;
Here “name” structure member is accessed through pointer variable stu.
16. 16
UNION :
Union is user defined data type used to stored data under unique variable name at
single memory location. Union holds value for one data type which requires larger storage
among their members.
Union follows the same syntax as structure with a major difference in terms of
storage. In structure every structure elements has their own storage location, whereas in union
all the members share the same location. So in a union there may be a number of elements
but only one member can be used at a time.
It defines different types of variable to share same space in memory.
To declare union data type, 'union' keyword is used.
Syntax:
union union_name
{
<data-type> element 1;
<data-type> element 2;
<data-type> element 3;
}union_variable;
Example:
union employee
{
int empid;
char name[20];
float salary;
}emp;
17. 17
In above example, it declares emp variable of type union. The union contains three
members as data type of int, char, float. We can use only one of them at a time.
MEMORY ALLOCATION :
Memory allocation for union
To access union members, we can use the following syntax.
Emp.empid
Emp.name
Emp.salary
Empid
salary
name
18. 18
Example:
#include <stdio.h>
#include <conio.h>
union employee
{
int id;
char name[50];
}emp;
void main()
{
clrscr();
printf("nt Enter employee id : ");
scanf("%d", &emp.id);
printf("nnt Enter employee name : ");
scanf("%s", emp.name);
printf("nn Employee ID : %d", emp.id);
printf("nn Employee Name : %s", emp.name);
getch();
}
output
Enter employee id : 101
Enter employee name : madhus
Employee ID : 101
Employee name : madhus
19. 19
Like structure members, we can access union members with statements like var.i,var.b, var.c.
While accessing value from an union member, we should make sure that we are accessing the
member in which the last value is assigned.
Difference between Structures & Union
Structure Union
We can access all the members of structure
at anytime.
Only one member of union can be accessed at
anytime.
Memory is allocated for all variables.
Allocates memory for variable which variable
require more memory.
All members of structure can be initialized
Only the first member of a union can be
initialized.
'struct' keyword is used to declare structure. 'union' keyword is used to declare union.
struct struct_name
{
structure element 1;
structure element 2;
----------
----------
structure element n;
}struct_var_nm;
union union_name
{
union element 1;
union element 2;
----------
----------
union element n;
union_var_nm;
eg
struct student
eg:
union student
20. 20
{
int marks;
float average;
char name[10];
memory allocation
int -2
float -4
name-10
total memory allocation=2+4+10
{
int marks;
float average;
char name[10];
memory allocation
only 10 bytes of memory will be allocated since
name data type will occupy maximum space of
memory over other data types
Advantages of union over structures
Union save memory space because the size of the union is equal to its largest sized
member.The size of the structure is the sum of the sizes of all structure members. So
Structure occupies a large space. Union are useful when there is a need to use only one of its
member at a time, But structure is used when there is a need to use all its members in a
program.
Storage classes
A storage class defines the scope (visibility) and life time of variables and/or
functions within a C Program.
21. 21
Local(internal) variables: are those which are declared within a particular function.
Global(external) variables: are those which are declared outside any function.
There are following storage classes which can be used in a C Program
auto
register
static
extern
auto - Storage Class
auto is the default storage class for all local variables.
Ex: auto int age;
This variable are private (local) to the function in which they are declared. If automatic
variables are not initialized they will contain garbage.
Program
#include <stdio.h>
int main()
{
int a=10;
check();
printf(“%dn”,a);
}
check()
{
int a = 5;
printf(“%dn”,a);
22. 22
}
Output:1
5
10
register - Storage Class
1. register is used to define local variables that should be stored in a register instead of
RAM. These variables are stored in one of the machine’s register and are declared
using register keyword. This is generally used for faster access.
Ex: register int m;
Program
#include<stdio.h>
#include<conio.h>
int main()
{
int a,b;
register int c;
clrscr();
printf("nEnter the Number 1 : ");
scanf("%d",&a);
printf("nEnter the Number 2 : ");
scanf("%d",&b);
c=a+b;
printf("nSum is : %d",c);
23. 23
getch();
return(0);
}
Output
Enter the Number 1 :5
Enter the Number 2 :7
Sum is :11
Explanation
we have declared two variables a,b. These two variables are stored in RAM. Another
variable c is declared which is stored in register variable.Register variables are stored in the
register of the microprocessor.Thus memory access will be faster than other variables.
Static - Storage Class
static is the default storage class for global variables. Static variables are initialized
only once, when the program is compiled.
Ex: static int count;
/* static variable */
#include <stdio.h>
int main(){
Check();
Check();
}
void Check(){
24. 24
static int count=0;
printf("%d",count);
count+=5;
}
Output:
0
5
extern - Storage Class
extern is used to give a reference of a global variable that is visible to ALL the program
files.
Ex: extern int count;
External variable can be accessed by any function. They are also known as global
variables and default value is zero. Variables declared outside every function are
external variables. These variables are active and alive throughout the entire program.
Program
int sum = 60 ;
void print()
{
extern int sum ;
printf("nSum : %d",sum);
}
void main()
{
extern int sum ;
printf("nSum : %d",sum);
display();
}
Output
25. 25
Sum : 60
Sum : 60
Explanation
If variable sum is defined outside the source code , then declaration using extern keyword is
required. The display function uses the extern keyword.
26. 26
THE C PREPROCESSOR
It is a program that processes the source code before it process by compiler. The C
Preprocessor is not part of the compiler, but is a separate step in the compilation process. In
simplistic terms, a C Preprocessor is just a text substitution tool. We'll refer to the C
Preprocessor as the CPP. It operates under the control of command lines or directives. All
preprocessor lines begin with #.
It is placed before the main source program. If any directives are in the program the
actions are taken first and the main source program taken over the compiler next.
The pre-processor is the computer program that processes the source program written in c
language before compilation.
it contains a collection of special statements called directives or pre-processor.
It is placed before the main () function in c programs.
Advantages of pre-processor
1. Programs are easier to develop by using the pre-processor directives.
2. The c codes will be portable and easy to read.
The common preprocessor directives are,
Directive Function
#include Used to include a file.
#define Used to define symbolic constant
#ifdef Used to test macro definition
#else Used to specify alternative in #ifdef
#undef Used to undefined a macro.
#if Used a condition
#endif Used to specify the end of #if
27. 27
The Preprocessor directives are classified into
1) File Inclusion directives
2) Macro substitution directives
3) Compiler control directives
File Inclusion directives:
This is used to include an external file, which contains functions or some other macro
definitions to our source program, so we need not rewrite functions and macros in our source
program
Syntax
#include <filename.h>
#include "filename.h"
filename.h is the name of the file
ex: #include <stdio.h>
Compiler control directives:
The unconditional directives are:
#include - Inserts a particular header from another file
#define - Defines a preprocessor macro
o #define identifier string/integer
#undef - Undefines a preprocessor macro
The conditional directives are:
#ifdef - If this macro is defined
#ifndef - If this macro is not defined
#if - Test if a compile time condition is true
#else - The alternative for #if
28. 28
#elif - #else an #if in one statement
#endif - End preprocessor conditional
Other directives include:
# - Stringization, replaces a macro parameter with a string constant
## - Token merge, creates a single token from two adjacent ones
Some examples of the above:
#define MAX_ARRAY_LENGTH 20
Tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for
constants to increase readability. Notice the absence of the semicolon(;).
#include <stdio.h>
#include "mystring.h"
Tells the CPP to get stdio.h from System Libraries and add the text to this file. The next line
tells CPP to get mystring.h from the local directory and add the text to the file.
Macro substitution directives:
i) simple macros
This is commonly used to define symbolic constants
#define A 10
macro substitutes ‘A’ with 10 in all occurrences in the source program.
ii) Argumented macros
The Argumented macros are used to define more complex and useful form of replacements in
the source program.
Syntax:
29. 29
#define identifier (v1 v2 v5….v4)string/integer
iii) Nested macros
The macros defined within another macro called nested macros.
Example:
#define A 5
This is a difference we must take note of.
#undef MEANING_OF_LIFE
#define MEANING_OF_LIFE 42
Tells the CPP to undefine MEANING_OF_LIFE and define it for 42.
#ifndef IROCK
#define IROCK "You wish!"
#endif
Tells the CPP to define IROCK only if IROCK isn't defined already.
#ifdef DEBUG
/* Your debugging statements here */
#endif
Tells the CPP to do the following statements if DEBUG is defined. This is useful if we pass
the -DDEBUG flag to gcc. This will define DEBUG, so we can turn debugging on and off on
the fly!
Parameterized Macros
One of the powerful functions of the C Pre Processor (CPP) is the ability to simulate
functions using parameterized macros. For example, we might have some code to square a
number:
30. 30
int square(int x)
{
return x * x;
}
We can instead rewrite this using a macro:
#define square(x) ((x) * (x))
Here is swap in action when using a macro:
#define swap(x, y) { int tmp = x; x = y; y = tmp }
Now we have swapping code that works. Why does this work? It's because the CPP just
simply replaces text. Wherever swap is called, the CPP will replace the macro call with the
defined text.
Example:
#define op L
main()
{
#ifdef L printf(“IBM”);
#else printf(“MS”);
#endif
}
31. 31
Unit V
PART A – 2 MARKS
1. What is structure?
A structure is a user defined data type which allows you to combine data items of
different kinds into a single unit. All the elements of a structure are stored at contiguous
memory locations. i.e., store heterogeneous data under unique name.
Keyword 'struct' is used to declare structure. The variables which are declared inside
the structure are called as 'members of structure'.
2. What is Union?
Union is user defined data type used to stored data under unique variable name at
single memory location. Union holds value for one data type which requires larger storage
among their members.
3. What are the differences between structure and union?
Structure Union
We can access all the members of
structure at anytime.
Only one member of union can be accessed at
anytime.
Memory is allocated for all variables.
Allocates memory for variable which variable
require more memory.
All members of structure can be
initialized
Only the first member of a union can be initialized.
'struct' keyword is used to declare
structure.
'union' keyword is used to declare union.
32. 32
4. What are advantages of union over structures
Union save memory space because the size of the union is equal to its largest sized
member. The size of the structure is the sum of the sizes of all structure members. So
Structure occupies a large space. Union are useful when there is a need to use only one of its
member at a time, But structure is used when there is a need to use all its members in a
program.
5. What is storage class ? List its types?
Storage classes
A storage class defines the scope (visibility) and life time of variables and/or
functions within a C Program.
There are following storage classes which can be used in a C Program
auto
register
static
extern
6. What is auto storage class?
auto is the default storage class for all local variables.
Ex: auto int age;
This variable are private (local) to the function in which they are declared. If automatic
variables are not initialized they will contain garbage.
7. What is static storage class?
static is the default storage class for global variables. Static variables are initialized
only once, when the program is compiled.
33. 33
Ex: static int count;
8. What is C Preprocessor?
It is a program that processes the source code before it process by compiler. The C
Preprocessor is not part of the compiler, but is a separate step in the compilation process. In
simplistic terms, a C Preprocessor is just a text substitution tool.
9. List out the various conditional directives.
1. #if
2. #ifdef
3. #ifdef
4. #elif
5. #elseif and
6. #endif
10. What are the different forms of macro substitution?
Simple macro
Argumented macro
Nested macros
11. What are the classification of preprocessor directives?
File Inclusion directives
Macro substitution directives
34. 34
PART-A (2 MARK)
1. Write any two different between structures and union.
2. List the common preprocessor directives.
3. What is the purpose of unions in C?
4. What is self-referential structure? Give an example.
5. Differentiate arrays from structures.
6. What are nested structures? Give an example.
PART –B
1. Explain about structures and unions suitable examples.
2. Draw a flowchart and write a C program to print student grade using structure
3. Write C program to read and write employee and their data of joining using Nested
structure.
4. Explain about structure declaration in C with suitable example.
5. Discuss about preprocessor facility in ‘C’.
6. Write a C program that gets and display the report of n students with their personal and
academic details using structures.
7. Write a C program to store the employee information details using structures and search
the particular employee information in employee information.
8. Explain the concept of storage classes with an example.
9. Write a C program to print the mark sheet for 10 students using structures.
10. Write the difference between structure and union.
11. Write a C program to create and print the student database with the following fields :
no,name,m1,m2,m3,m4,m5,total and average. If the student has failed in any of the
subjects, assign FAIL else based on the average, assign first class with distinction or,
first class or second class.
12. Create a employee database with 4 employees using nested structure : no, name and
address. Let the nested structure be salary with fields basic,hra,da,ta and cca. Display the
details of employees with salary >6000.
13. Define a data type for storing complex numbers and implement addition, subtraction,
multiplication operations for the defined type.
14. Create a payroll application using structure with the following details :
DA= 15% of basic
HRA= 20% of basic
TA=18% of basic
35. 35
Gross salary= basic+ HRA + DA + TA
Deduction= PF+ tax;
NetSalary=Gross Salary – Deduction
15. Write a C program using structure to print the details of book. Use array of structure