Sunday, 5 April 2020

Array of Structures in C with example


Like normal arrays of integer, floats etc which have elements of type integer, float respectively, array of structures is nothing but a collection of structures. It means elements of array will be structures not normal type ( integer, float etc.).

Consider following example:

  #include<stdio.h>
   struct student{
       int rollno;
       float marks;
   };

int main(){
   struct student s1;
   s1.rollno=12;
   s1.marks=92.5;
  
   printf("\nStudent 1 Details\n");
   printf("\nRoll No:%d",s1.rollno);
   printf("\nMarks:%.2f\n",s1.marks);

 return 0;
}

In above program, we have declared one structure variable s1 for one student. What if we want to store roll no and marks of 40 students of a class? We have two options either we declare 40 structure variables (s1 to s40) or simply create an array of structures of size 40 as explained in below program:
 
#include<stdio.h>
   struct student{
       int rollno;
       float marks;
   };

int main(){
   struct student s[5];
   int i;

   printf("\nEnter Students Details\n");
   for(i=0;i<5;i++){
       printf("\nEnter Roll No and marks of student %d\n",i+1);
       scanf("%d",&s[i].rollno);
       scanf("%f",&s[i].marks);
   }
  
   printf("\nStudents Details\n");
   for(i=0;i<5;i++){
      printf("\nRoll No and marks of student %d are %d and %f respectively\n",i+1,s[i].rollno,s[i].marks);
   }

 return 0;
}

Output:



You may also like:
 Structure in C
 Typedef in C with examples
 Self Referential Structures in C with Example

Please comment and share if you find it useful.

No comments:

Post a Comment