Array of Structure in C
What is Array of Structure in C?
Structure is user defined data type which can store similar data items but of different data types.Structure can store different data types.Normally it represents a single record but if we have to store more record then we make array of structure.
Syntax to declare variable of array of Structure
struct structureName
{
dataType member1;
dataType member2;
dataType member3;
...
}variable_name[size];
Another way of creating variable of array of structure
struct structureName
{
dataType member1;
dataType member2;
dataType member3;
...
};
void main()
{
struct structureName variable_name[size];
}
Example to store the data of five students:
#include<stdio.h>
struct student
{
int rollno;
float fee;
char name[10];
};
void main()
{
struct student st[5]; //array of structure
int i;
for(i=0;i<=4;i++)
{
printf("Enter rollno ");
scanf("%d",&st[i].rollno);
printf("Enter fee ");
scanf("%f",&st[i].fee);
printf("Enter name ");
scanf("%s",&st[i].name);
printf("\n");
}
for(i=0;i<=4;i++)
{
printf("\nRollno is %d",st[i].rollno);
printf("\nFee is %f",st[i].fee);
printf("\nName is %s",st[i].name);
printf("\n\n");
}//end of loop
}//end of main
Output
Enter rollno 10
Enter fee 2000
Enter name neha
Enter rollno 20
Enter fee 3000
Enter name priya
Enter rollno 30
Enter fee 4000
Enter name riya
Enter rollno 40
Enter fee 5000
Enter name sunil
Enter rollno 50
Enter fee 6000
Enter name navneet
Rollno is 10
Fee is 2000.000000
Name is neha
Rollno is 20
Fee is 3000.000000
Name is priya
Rollno is 30
Fee is 4000.000000
Name is riya
Rollno is 40
Fee is 5000.000000
Name is sunil
Rollno is 50
Fee is 6000.000000
Name is navneet
What is Array within Structure in C?
Array within Structure means when we declare an array of data members of structure inside the block of structure.Let's understand it with an example:
Example to find the average marks of nine subjects through structures
#include<stdio.h>
struct student
{
char name[10];//array within structure
int subject[9];//array within structure
};
void main()
{
struct student st;
int sum=0,avg,i;
printf("Enter name");
gets(st.name);
for(i=0;i<9;i++)
{
printf("Enter the marks of %d subject",i+1);
scanf("%d",&st.subject[i]);
sum=sum+st.subject[i];
}
avg=sum/9;
printf("\n Average of nine subjects is %d",avg);
}//end of main
Output
Enter name sunil
Enter the marks of 1 subject80
Enter the marks of 2 subject80
Enter the marks of 3 subject80
Enter the marks of 4 subject80
Enter the marks of 5 subject80
Enter the marks of 6 subject80
Enter the marks of 7 subject80
Enter the marks of 8 subject80
Enter the marks of 9 subject80
Average of nine subjects is 80