Array of structures

·

Each element of the array itself is a structure. See the example shown below. Here we want to store data of 5 persons for this purpose, we would be required to use 5 different structure variables, from sample1 to sample 5. To have 5 separate variable will be inconvenient.

# include "stdio.h"
main( )
{
struct person
{
char name [25];
char age;
};

struct person sample[5];
int index;
char into[8];
for( index = 0; index <5;>
{
print(“Enter name;”);
gets(sample [index]. name);
printf(“%age;”);
gets(info);
sample [index]. age = atoi (info);
}
for (index = 0; index <5;>
{
printf(“name = %5\n”, sample [index]. name);
printf(“Age = %d \n”, sample [index]. age);
getch( );
}
}
The structure type person is having 2 elements:
Name is an array of 25 characters and character type variable age

Using the statement:
struct person sample[5]; we are declaring a 5 element array of structures. Here, each ele- ment of sample is a separate structure of type person.
We, then defined 2 variable indexes and an array of 8 characters’ info.

Here, the first loop executes 5 times, with the value of index varying from 0 to 4. The first printf statement displays. Enter name gets( ) function waits for the input string. For the first time this name you enter will go to sample[0]. name. The second printf display age the number you type is will be 5 stored as character type, because the member age is declared as character type. The function atoi( ) converts this into an integer. atoi stands for alpha to integer. This will be stored in sample[0] age. The second for loop in responsible for printing the information stored in the array of structures.

About Me

Blog Archive