C Array of Structures | Arrays of Structures | Array of Structure in C

In this article C array of structures we give the information about arrays of structures, example and array of structure program in c.

Arrays of Structures:

We use structures to describe the format of a number of related variables. For example, in analyzing the score obtained by the cricket match of players, we may use a template to describe players name and score obtained in various matches and then declare all the players as structure variables. In such cases, we may declare an array of structures, each elements of the array representing a structure variable.

For example:

struct c_match players[11];

Defines an array called players, that consists of 11 elements. Each element is defined to be of type sturct c_match. Consider the following declaration:

struct scores

{

int match1;

int match2;

int match3;

};

main()

{

struct score player[3] = {{40, 72, 90}, {51, 81, 36}, {40, 62, 91} };

this declares the players as an array of three elements player[0], player[1] and  player[2]   and initializes their members as follows:

player[0].match1 = 40;

player[0].match2 = 72;

player[0].match3 = 90;

………

………

Player[2].match3 = 91;

Example:

/* Write a program to calculate the player-wise totals and store them as a part of the structure.

Program:

*/

#include<stdio.h>

#include<conio.h>

struct score

{

int match1;

int match2;

int match3;

int total;

};

void main()

{

int i;

struct score player[3] = {{40, 72, 90,0}, {51, 81, 36,0}, {40, 62, 91,0} };

clrscr();

for( i=0; i<3; i++)

{

player[i].total=player[i].match1+player[i].match2+player[i].match3;

}

printf(“\nPlayer      Total\n”);

for( i=0; i<3; i++)

{

printf(“Player[%d]           %d\n”, i+1, player[i].total);

}

getch();

}

OUTPUT:

Player               Total

Player[1]             202

Player[2]            168

Player[3]            193

// Arrays within structure

#include<stdio.h>
#include<conio.h>
struct marks
{
int sub[3]; // array variable
int tot;
};
void main()
{
struct marks stud[3]={45,67,81,0,75,53,69,0,57,36,71,0};
int i,j;
clrscr();
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
stud[i].tot=stud[i].tot+stud[i].sub[j];
}
}
printf(“\n\n Student Total\n”);
for(i=0;i<3;i++)
printf(“\n stud[%d] %d”,i+1,stud[i].tot);
getch();
}

Related Link:

Some More: DBMS/ WT/ DMDW

Santosh Nalawade

Work as Assistant Professor and Web Developer.

Leave a Reply

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