Array within structure

Array within a structure is a concept in which a structure that we define in the program consists of a variable array in it.

Observe the below program,

  • The below program is related to the details of two students.
  •  Here, inside the structure defined, we have declared the integer array marks[5], which is an array within a structure.
  •  As we have defined the structure globally, we can declare the structure variable anywhere in the program.
  •  We have declared two structure variables stu1 and stu2, inside the main function.
  • The structure variables declared consists of all the variable names defined inside the structure “student” datatype, as both the variables stu1 and stu2 declared are “student” data type.
  • Int array marks[5] will take the input as marks of five subjects of stu1 and stu2.
  • We took the input of roll_no, name, and marks of five subjects of both the students.
  •  We added the five subject marks of both the students and store the total in variable total1 and total2.
  •  Finally, we printed all the information about both the student.
  •  Observe the program and output.

 Below is the diagrammatical representation of the stu1 structure variable.

 
 
array-structure-c

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 
#include<stdio.h>

struct student
{
 int roll_no;
 char name[10];
 int marks[5];
};

int main()
{
 struct student stu1,stu2;
 int i,sum1=0,sum2=0;
 
 printf("Enter the rollno of first student and second student:\n");
 scanf("%d %d", &stu1.roll_no,&stu2.roll_no);
 printf("Enter the name of first student and second student:\n");
 scanf("%s %s",stu1.name,stu2.name);
 printf("Enter the marks of five subject of first student and second student:\n");
 for(i=0;i<5;i++)
 {
  scanf("%d %d",&stu1.marks[i],&stu2.marks[i]);
  sum1=sum1+stu1.marks[i];
  sum2=sum2+stu2.marks[i];
 }
 printf("***************************\n");
 printf("Print the first student roll_no, name, marks of five subject and total marks:\n");
 printf("rollno= %d \n name= %s \n",stu1.roll_no,stu1.name);
 printf("marks of five subject:\n");
 for(i=0;i<5;i++)
 {
   printf("%d ",stu1.marks[i]);
 }
 printf("\nTotal= %d",sum1);
printf("\n***************************\n");
 printf("Print the second student roll_no, name, marks of five subject and total marks:\n");
 printf("rollno= %d \n name= %s \n",stu2.roll_no,stu2.name);
 printf("marks of five subject:\n");
 for(i=0;i<5;i++)
 {
   printf("%d ",stu2.marks[i]);
 }
 printf("\nTotal= %d",sum2);

 return 0;
}

output:

array-structure-c