Module 4 Structures
Module 4 Structures
Structures: Basics of Structures, Nested Structures, Arrays of Structures, Arrays within structures,
Structures and functions, pointers and structures, Self-referential structures, Unions.
Introduction to Structure
• Problem:
• – How to group together a collection of data items of different
types that are logically related to a particular entity???
Structure
• A structure is a collection of variables of
• different data types under a single name.
• The variables are called members of the structure.
• The structure is also called a user-defined data type.
3
Defining a Structure
• Syntax:
struct structure_name
{
data_type member_variable1;
data_type
member_variable2;
………………………………;
data_type member_variableN;
};
Once structure_name is declared as new data type, then
variables of that type can be declared as:
struct structure_name structure_variable;
Note: The members of a structure do not occupy
memory until they are associated with a structure_variable.
4
• Example
struct student
{
char name[20];
int roll_no;
float marks;
char gender;
long int
phone_no;
};
6
Defining a structure…
• The structure definition and The use of structure_name is
variable declaration be
can
combined as: optional. struct
struct student {
{ char name[20];
char name[20]; int roll_no;
int roll_no; float marks;
float marks; char gender;
char gender; long int
long int phone_no;
phone_no; }st1, st2, st3;
}st1, st2, st3;
7
ACCESSING MEMBERS OF STRUCTURE :
To access the members of the structure, a variable for the structure
has to be created.
Syntax :
Struct tag variablename;
ARRAYS STRUCTURES
Roll : 10
Name : Kumar
Total : 223
Average : 74.00000
Write a C program to maintain record of N Employee detail using array of structure with 3
fields: ID, Name and Salary And print details of employees whose salary is above 10000.=
int main()
#include<stdio.h> {
printf(“The Employee Details:\n”);
printf(“Eid \t Name \t Salary\n”);
struct employee for (i=0;i<n;i++)
struct employee e[10];
{ printf(“%d \t %s \t %d \
int n,i;
n”,e[i].eid,e[i].name,e[i].salary);
int eid;
printf(“Enter the no.of employees\n”);
char name[20]; scanf(“%d”,&n);
printf(“Employee salary above 10000\n”);
int salary; printf(“Enter the Employee details:\n”);
for(i=0;i<n;i++)
{
}; for(i=0;i<n;i++)
if(e[i].salary>10000)
{
printf(“%s\n”,e[i].name);
printf(“Enter %d employee detail:\n”);
}
printf(“\nEnter the EID: ”);
}
scanf(“%d”,&e[i].eid);
printf(“\nEnter the Name: ”);
scanf(“%s”,e[i].name);
printf(“\nEnter the salary: ”);
scanf(“%d”,&e[i].salary);
}
Enter the no.of employees Enter the salary: 2000 The Employee Details:
3 Enter 3 employee detail: Eid Name Salary
11 arun 12000
Enter the Employee Enter the EID: 33 22 rao 2000
details:
33 bharath 25000
Enter 1 employee detail: Enter the Name: bharath Employee salary above 10000
arun
Enter the salary: 25000 bharath
Enter the EID: 11