Array Within Structure in C with Examples

In C programming, we can have structure members of type arrays. Any structure having an array as a structure member is known as an array within the structure. We can have as many members of the type array as we want in C structure.

To access each element from an array within a structure, we write structure variables followed by dot (.) and then array name along with index.

Example: Array Within Structure


struct student
{
 char name[20];
 int roll;
 float marks[5]; /* This is array within structure */
};

In above example structure named student contains a member element marks which is of type array. In this example marks is array of floating point numbers.

If we declare structure variable as:


struct student s;

To access individual marks from above structure s, we can write s.marks[0], s.marks[1], s.marks[2], and so on.

C Program: Array Within Structure


#include<stdio.h>

struct student
{
 char name[20];
 int roll;
 float marks[5]; /* This is array within structure */
};

int main()
{
 struct student s;
 int i;
 float sum=0, p;

 printf("Enter name and roll number of students:\n");
 scanf("%s%d",s.name,&s.roll);
 printf("\nEnter marks obtained in five different subject\n");

 for(i=0;i< 5;i++)
 {
  printf("Enter marks:\n");
  scanf("%f",&s.marks[i]);
  sum = sum + s.marks[i];
 }

 p = sum/5;
 printf(“Student records and percentage is:\n”);
 printf("Name : %s\n", s.name);
 printf("Roll Number : %d\n", s.roll);
 printf("Percentage obtained is: %f", p);
 
 return 0;
}

Output

The output of the above program is:

Enter name and roll number of students:
Neelima
171

Enter marks obtained in five different subject
Enter marks:
78
Enter marks:
87
Enter marks:
92
Enter marks:
89
Enter marks:
96

Student records and percentage is:
Name: Neelima
Roll Number: 171
Percentage obtained is: 88.40