Array of Structure in C

by | Aug 16, 2022 | C

Home » C » Array of Structure in C

In the previous programs, we just declared two variables to store the data of two students. We can use an array of structures to store the data of large strength, say 10 or 100. Although we can declare as many variables as we want, the declaration of 100 such variables of the same data type doesn’t reflect good programming skills. Thus, making an array for such a task is a better option.

We will write a program to store the basic information of 5 students.

Program

#include<stdio.h>
#include<string.h>
struct student
{
char name[20];
int roll_no;
int age;


};
int main()
{
printf("Enter your details:\n");
struct student S[5];
int i;
for(i=0;i<5;i++)
{
printf("\nStudent %d\n",i+1);
printf("Enter roll no:");
scanf("%d",&S[i].roll_no);
printf("Enter name:");
scanf("%s",&S[i].name);
printf("Enter age:");
scanf("%d",&S[i].age);


}
printf("Details of the students are as below:\n");
for(i=0;i<5;i++)
{
printf("\nStudent %d\n",i+1);
printf("Roll no: %d\n",S[i].roll_no);
printf("Name: %s\n",S[i].name);
printf("Age: %d\n",S[i].age);
}
return 0;


}

 

Output

Explanation

The code is simple enough. The first ‘for’ loop is used to take inputs from the user and the next one is used to print the details entered by the user. Here, S[0] stores the information of the first student, S[1] for the second one, and so on.

See the code below for some more changes.

#include<stdio.h>
#include<string.h>
int main()
{
struct student
{
char name[20];
int roll_no;
int age;


};
struct student s1={"ABC",1903119,21 };
struct student s2;
s2=s1;


printf("Student s2\n");
printf("Roll no: %d\n",s2.roll_no);
printf("Name: %s\n",s2.name);
printf("Age: %d\n",s2.age);
return 0;


}

 

Output

Explanation

You should be clear from the above code two important things.

The structure can be defined inside and outside the ‘main’ function. Earlier, we wrote all programs by defining them outside the ‘main’ function, but in the above code, we define it inside the ‘main’ function, and both are completely valid.

We can copy one structure into the other by simply equating the two. s2=s1; this statement means all the elements of ‘s1’ are copied to ‘s2’.

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author