C programs to differentiate array of structures and arrays within a structure

CServer Side ProgrammingProgramming

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\n\n");
   for(i = 0; i <= 2; i++)
   printf("Student[%d] %d\n", i+1,student[i].total);
   printf("\n SUBJECT TOTAL\n\n");
   printf("%s %d\n%s %d\n%s %d\n",
      "Subject 1 ", total.sub1,
      "Subject 2 ", total.sub2,
      "Subject 3 ", total.sub3);
   printf("\nGrand Total = %d\n", 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\n\n");
   for(i = 0; i <= 2; i++)
   printf("Student[%d] %d\n", i+1, student[i].total);
   printf("\nSUBJECT TOTAL\n\n");
   for(j = 0; j <= 2; j++)
   printf("Subject-%d %d\n", j+1, total.sub[j]);
   printf("\nGrand Total = %d\n", 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
raja
Updated on 26-Mar-2021 06:50:51

Advertisements