Differentiate Array of Structures and Arrays within a Structure in C



In C programming language, the most common use of structure is an array of structures.

To declare an array of structures, first the structure must be defined and then, an array variable of that type has to be defined.

For example,

struct book b[10];//10 elements in an array of structures of type ‘book’

Example

Following is the C program for the array of structures −

 Live Demo

struct marks{
   int sub1;
   int sub2;
   int sub3;
   int total;
};
main(){
   int i;
   struct marks student[3] = {{20,17,11,10},
      {175,23,169,10},
      {27,56,27,01}};
   struct marks total;
   for(i = 0; i <= 2; i++){
      student[i].total = student[i].sub1 +
      student[i].sub2 +
      student[i].sub3;
      total.sub1 = total.sub1 + student[i].sub1;
      total.sub2 = total.sub2 + student[i].sub2;
      total.sub3 = total.sub3 + student[i].sub3;
      total.total = total.total + student[i].total;
   }
   printf(" STUDENT TOTAL

");    for(i = 0; i <= 2; i++)    printf("Student[%d] %d
", i+1,student[i].total);    printf("
SUBJECT TOTAL

");    printf("%s %d
%s %d
%s %d
",       "Subject 1 ", total.sub1,       "Subject 2 ", total.sub2,       "Subject 3 ", total.sub3);    printf("
Grand Total = %d
", total.total); }

Output

When the above program is executed, it produces the following output −

STUDENT TOTAL
Student[1] 48
Student[2] 367
Student[3] 110
SUBJECT TOTAL
Subject 1 4200462
Subject 2 96
Subject 3 223
Grand Total = 525

Example

Following is the C program for an array within structure −

 Live Demo

main(){
   struct marks{
      int sub[3];
      int total;
   };
   struct marks student[3] =
      {145,50,11,10,175,50,19,10,20,30,25,10};
   struct marks total;
   int i,j;
   for(i = 0; i <= 2; i++){
      for(j = 0; j <= 2; j++){
         student[i].total += student[i].sub[j];
         total.sub[j] += student[i].sub[j];
      }
      total.total += student[i].total;
   }
   printf("STUDENT TOTAL

");    for(i = 0; i <= 2; i++)    printf("Student[%d] %d
", i+1, student[i].total);    printf("
SUBJECT TOTAL

");    for(j = 0; j <= 2; j++)    printf("Subject-%d %d
", j+1, total.sub[j]);    printf("
Grand Total = %d
", total.total); }

Output

When the above program is executed, it produces the following output −

STUDENT TOTAL
Student[1] 216
Student[2] 254
Student[3] 85
SUBJECT TOTAL
Subject-1 4200548
Subject-2 130
Subject-3 71
Grand Total = 555
Updated on: 2021-03-26T06:50:51+05:30

722 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements