0% found this document useful (0 votes)
15 views

CO110 Computer Programming10

The document discusses structures and unions in C programming. Structures allow grouping of related data types under one name, while unions provide a way to save memory by allowing only one member to be active at a time. The document explains structure and union definitions, initialization, accessing members, nested structures, arrays of structures and provides examples.

Uploaded by

sauravk2424
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

CO110 Computer Programming10

The document discusses structures and unions in C programming. Structures allow grouping of related data types under one name, while unions provide a way to save memory by allowing only one member to be active at a time. The document explains structure and union definitions, initialization, accessing members, nested structures, arrays of structures and provides examples.

Uploaded by

sauravk2424
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Chapter 10

Structures and Unions


Need for Structures
In C, one of the most important issues is to bundle data
which are of different data types but are logically related
and is to be operated on as a whole.
For example: If we want to store the information about
person about his/her name, aadhaar number and salary,
we can create these information separately. But a better
approach will be a collection of these information under
single name since all these information are related to the
same person.
These type of problem can be handled in C
programming using structures.
What is a structure?
 An structure in C is a user defined data type in which the
members of the structure need not be of the same data
type.
• The keyword struct is used for creating a structure.
• The general syntax for a structure declaration is
struct structure_name
{
data_type member1; The structure declaration end
with a semicolon.
data_typez member2; The members of the structure
.. are also separated with a
data_type memeber; semicolon
};
Structure Definition
 struct person
{ Here the members of the structure
are of integer, string and float data
char name[50]; types.
int id_no; Thus the size of a structure variable
will be the sum of the constituent
float salary; data types.
}; i.e 50*+4*+4* =56 bytes

* Depends on the compiler

Structure definition occurs before structure variable


declaration
Structure Variable Declaration
 When a structure is defined, it creates a user-defined type
but, no storage is allocated.
For the structure person, variable can be declared
struct person
{
char name[50];
int id_no;
float salary;
}; Here p1 is variable of type
struct person
struct person p1;

After the above structure has been defined we can use struct person in
the same manner as we can use int, float, char , double.
 We can also combine definition and variable declaration in one single
statement in the below fashion.
struct person
{
char name[50];
int id_no;
float salary;
} per1;
 We can use the keyword typedef to rename the struct person data type.
typedef struct
{ typedef is used to create an
. ..; alias for a datatype, variable etc
} Person;
Now we can use the statement
Person per1, per2;
Accessing members of a structure
 There are two types of operators used for accessing
members of a structure.
1. Dot operator(.)
2. Structure pointer operator(->) ( using pointer concept)

Any member of a structure can be accessed as:


structure_variable_name.member_name
z

Suppose, we want to access salary for variable per2


per2.salary
Array of structures
 We can also declare an array of structures at the time
of structure definition.
struct person
{
Also we can have arrays
char name[50]; as structure members
int id_no;
float salary;
} per[50];
Structures within structures
 Structures can be nested within another structure in C
programming.
 We can write one structure as a member of another
structure.
 For E.g consider the following declarations.

struct day struct person


{ {
int date; char name[20];
int id_no; Here we access the fields as
int month; p1.dob.date;
int year; float salary;
struct day dob; p1.dob.month;
}; p1.dob.year;
}p1;
Structures within structures
 Structures can also be nested within another structure
definition in C programming.
 For E.g consider the following declaration.

struct person
{
char name[20]; Note struct day definition is within
int id_no; struct person definiton.
float salary;
Also we have declared a variable of type
struct day struct day named “dob” .
{
int date;
Here we access the fields in the same manner as previously
int month; p1.dob.date;
int year; p1.dob.month;
}dob; p1.dob.year;
}p1;
Structure Initialization
 Initializing a structure is the task of giving values to
the members of the structure.
 This can be done in 2 manners
1. At Compile time
Here values are given to the structure members by the
programmer in the code itself. Here the values are harcoded.
2. At Run time.
Here values are given to the structure members by the user using
appropriate printf() and scanf() functions. That is the values are
not hardcoded.
Structure Initialization
1. At Compile Time
Consider the example
struct person Here the per1 and per2 structure
variables are given values in the
{ given syntax
char name[50]; 1. = operator between values and
structure variable.
int id_no; 2. enclosed within flower brackets
3. Seperated by a comma
float salary; 4. Terminated by a semicolon.
} per1 = { “mahesh”, 250, 5000.70},
per2= { “suresh”, 300, 5001.00};
Structure initialization
In the previous example the variable initialization was with along with
the structure definition.
struct person Here the per1 and per2 structure
{ variables are given values not
char name[50]; during the structure definition.
int id_no;
float salary; But after the definition in main
}; function. This creates a local
structure variable.
struct person per1= { “mahesh”,250, 5000.70}; E.g per2
void main()
{ Also the initialization can be done
struct person per2= { “suresh”, 300, 5001.00}; before main which will create a
- - - -- -- - -; global structure variable.
- - - - -- --- ---- --; E.g per1
}
Structure Program
Member initialization at Run Time
#include<stdio.h> scanf(“ %d”, &per[i].id_no);
struct person scanf(“ %f”,&per[i].salary);
{ char name[50]; }
int id_no;
float salary; printf(“The persons details entered are: \n “);
} per[10]; printf(“ Name \t Id \t Salary\n”);
void main() for(i=0; i< size; i++)
{ int size; {
printf(“Enter the number of persons: “); printf(“%s \t”, per[i].name);
scanf(“ %d”,&size); printf(“%d”\t, per[i].id_no);
printf(“Enter the persons details: \n “); printf(“%f \t”,per[i].salary);
for(i=0; i< size; i++) }
{ }
gets( per[i].name);
Unions
 Unions are similar to structures syntactically.
union person Union members occupy the same
{ memory location.
char name[50];
int id_no; In a union, the memory allocated will be
float salary; equal to the size of the largest member.
}; E.g: Here Union size = 50, whereas
structure size = 58
By using Union we can
save a lot of memory In a union, only one member will be
which otherwise is active at a time.
unutilized.

Unions are useful in developing applications, where values need


not be assigned to members at the same time.
Eg in case of Embedded system applications.
Unions Program
#include<stdio.h> switch( choice)
union person { case 1 : printf(“Please enter names: \n “);
{ char name[50]; for(i=0; i< size; i++)
int id_no; gets(per[i].name);
} per[10]; printf(“Entered names are: \n “);
void main( ) for(i=0; i< size; i++)
{ int size, I, choice ; printf(“%s \t”, per[i].name);
printf(“Enter the number of persons: break;
“); case 2: printf(“Please enter IDs: \n “);
scanf(“ %d”, &size); for(i=0; i< size; i++)
scanf(“ %d”, &per[i].id_no);
printf(“1. Name 2. ID “); printf(“Entered IDd are: \n “);
printf(“ Please select the member: \n”); for(i=0; i< size; i++)
scanf(“ %d”, &choice); printf(“%s \t”, per[i]. id_no);
}
}
Bitfields
 Bitfields is a memory conserving technique which helps a programmer
to make effective use of memory.
In the given structure we have 2
members -> Age and Gender
 struct person
Now the range of age is from 0 – 120
{ int age; years at best.
char gender; Also the gender can have only 2
values Male(0) or Female (1).
} per;

 The size of the structure variable “ per” is 2+1 = 3 bytes or 24 bits.


 But the feasible values need only 7bits for Age : 0-127 and 1 bit for
Gender : Male/Female . So in all 7+1 = 8 bits.
 So we would be wasting 32 (or 16 )bits for each structure variable.
Bitfields Definition
struct
{ type [member_name] : width ;
};
The type field can have only int,
unsigned int and singned int.

Example
struct person
{ unsigned int age : 7;
int gender : 1;
};
Bitfields Program
#include<stdio.h> Output :
struct The code will compile with
{ unsigned int age : 3; warning and will give the
} Age; following output

int main( ) Age.age : 5


{ Age.age = 5; Age.age : 0

printf( "Age.age : %d\n", Age.age );


Age.age = 8;
The 2nd value has a 0 since we
printf( "Age.age : %d\n", Age.age ); require 4 bits to store the
value 8 and the size alloted is
} only 3 bits.
Structure Programs
 Define a structure Student with the fields Name, Roll_No,
Marks in 5 Subjects, Total and Grade. Create an array of
structures taking the class strength from the user and
populate the Name, Roll_No and Marks fields of the all
students. Compute the Total and assign the grade to the
student based on the following chart.
Total Grade Display the output in the following format
>=450 A
>=400 B NAME ROLL MARK 1 MARK2 …. TOTAL GRADE
>=300 C
Ram 1 50 45 …. . 348 C
>=250 D
<250 F
Shyam 2 80 70 …. 470 A
Program to find grade of students in a class
#include<stdio.h>
struct student
{ char name[50];
int Roll_no, marks[5],total;
char grade;
} S1[10];
void main()
{ int class_strength, i, j ;
printf(”What is the class strength?”);
scanf(“ %d”, &class_strength );
printf(“Enter student details: \n “);
for(i=0; i< class_strength ; i++)
{ gets(S1[i].name);
scanf(“ %d”, &S1[i].Roll_no);
Program to find grade of students in a class
for (j=0, S1[i].total =0; j<5; j++)
{ scanf(“ %d”,&S1[i].marks[j]);
S1[i].total += S1[i].marks[j];
}

S1[i]. Grade = S1[i].total>449 ? ’A’ : S1[i].total>399 ?


’B’ : S1[i].total>299 ? ’C’ : S1[i].total>249 ? ’D’ : ’F’;

}
printf(“The student details of Section S1 are: \n “);
printf(“ Name \t Roll No \t Marks1 \t Marks2 \t Marks3
\t Marks4 \t Marks5 \t Total \t Grade\n”);
Program to find grade of students in a class
for(i=0; i< class_strength ; i++)
{ printf(“%s\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t
%c\n” , S1[i].name, S1[i].Roll_no,
S1[i].marks[0], S1[i].marks[1],
S1[i].marks[2], S1[i].marks[3],
S1[i].marks[4], S1[i].total, S1[i].grade );
}
}
Program to display the student list in descending
order total marks scored

NAME ROLL MARK 1 MARK2 …. TOTAL GRADE

Shyam 2 80 70 …. 520 A

Ram 1 50 45 …. . 348 C
Name Roll No Marks1 Marks2 Marks3 Marks4 Marks5 Total Grade
Rama Shasrty 12344 89 90 78 83 70 410 B
Shlipa Rani 11234 56 34 50 67 64 271 D
Mansoor Dsouza 13456 78 12 78 56 99 323 C
Raveena Yasmeen 10345 89 45 67 89 65 355 C
Ramesh Babu 10444 39 45 17 19 35 155 F
Robert Yashoda 17565 99 95 97 99 96 486 A
Udyan Basu 10345 89 45 67 89 65 355 C

S1 Student list in descending order of total marks Scored


Name Roll No Marks1 Marks2 Marks3 Marks4 Marks5 Total Grade
Robert Yashoda 17565 99 95 97 99 96 486 A
Rama Shasrty 12344 89 90 78 83 70 410 B
Raveena Yasmeen 10345 89 45 67 89 65 355 C
Udyan Basu 10345 89 45 67 89 65 355 C
Mansoor Dsouza 13456 78 12 78 56 99 323 C
Shlipa Rani 11234 56 34 50 67 64 271 D
Ramesh Babu 10444 39 45 17 19 35 155 F
Program to find grade of students in a class
#include<stdio.h>
struct student
{ char name[50];
int Roll_no, marks[5],total;
char grade;
} S1[10];
void main( )
{ int class_strength, i, j ,t;
printf(”What is the class strength?”);
scanf(“ %d”, &class_strength );
printf(“Enter student details: \n “);
for(i=0; i< class_strength ; i++)
{ getsS1[i].name);
scanf(“ %d”, &S1[i].Roll_no);
Program to find grade of students in a class
for (j=0, S1[i].total =0; j<5; j++)
{ scanf(“ %d”,&S1[i].marks[j]);
S1[i].total += S1[i].marks[j];
}

S1[i]. Grade = S1[i].total>449 ? ’A’ : S1[i].total>399 ?


’B’ : S1[i].total>299 ? ’C’ : S1[i].total>249 ? ’D’ : ’F’;

}
printf(“The student details of Section S1 are: \n “);
printf(“ Name \t Roll No \t Marks1 \t Marks2 \t Marks3
\t Marks4 \t Marks5 \t Total \t Grade\n”);
Program to find grade of students in a class
for(i=0; i< class_strength ; i++)
{ printf(“%s\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t
%c\n” , S1[i].name, S1[i].Roll_no,
S1[i].marks[0], S1[i].marks[1],
S1[i].marks[2], S1[i].marks[3],
S1[i].marks[4], S1[i].total, S1[i].grade);
}
}
Program to find grade of students in a class

for(i=0; i< class_strength - 1 ; i++)


{ for (j=o; j<class_strength-i-1; j++)
if (S1[j].total < S1[j+1].total)
{ t = S1[j].total;
S1[j].total = S1[j+1].total;
S1[j+1].total = t;
}
}
Program to find grade of students in a class
printf(“S1 Student list in descending order of total
marks Scored\n “);
printf(“ Name \t Roll No \t Marks1 \t Marks2 \t Marks3 \t
Marks4 \t Marks5 \t Total \t Grade\n”);
for(i=0; i< class_strength ; i++)
{ printf(“%s\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t
%c\n” , S1[i].name, S1[i].Roll_no,
S1[i].marks[0], S1[i].marks[1],
S1[i].marks[2], S1[i].marks[3],
S1[i].marks[4], S1[i].total, S1[i].grade );
}
}
Any doubts ?
Program to find grade of students in a class
#include<stdio.h>
struct student
{ char name[50];
int Roll_no, marks[5],total;
char grade;
} S1[10], t ;
void main()
{ int class_strength, i, j ;
printf(”What is the class strength?”);
scanf(“ %d”, &class_strength );
printf(“Enter student details: \n “);
for(i=0; i< class_strength ; i++)
{ gets(“ %s”, S1[i].name);
scanf(“ %d”, &S1[i].Roll_no);
Program to find grade of students in a class

for(i=0; i< class_strength - 1 ; i++)


{ for (j=o; j<class_strength-i-1; j++)
if (S1[j].total < S1[j+1].total)
{ t = S1[j];
S1[j] = S1[j+1];
S1[j+1] = t;
}
}
What is a structure and the need of structures in C
programming?
Can we have nesting of structures in C ? If yes explain
the same with a detailed example.
Give differences between arrays and structures in C
Give differences between structures and Unions in C
What are Bitfields in C? Explain with a suitable
example.

You might also like