C program to illustrate the use of array of structures

Array of structures in c programs are created using indices. They are created and accessed using [] and dot(.) operator.

array-of-structures-program-in-c, c program array of structures


Source code:

#include<stdio.h>
struct test1
{
    char a;
    int i;
    float u;
}m[3];                       //Step 1
int main()
{
     int n;
     for(n=0;n<=2;++n)
      {
          printf("\n Enter ch, in, fl :");
          fflush(stdin); /* clear stdin stream */
          scanf("%c %d %f",&(m[n].a),&(m[n].i),&(m[n].u));   //Step 2
          fflush(stdout); /* clear stdout stream */
          printf("\n a=%c, i=%d, u=%f", m[n].a, m[n].i, m[n].u);  //Step 3
      }
return 0;
}


edit-code-image

Sample test cases:

1.   Enter ch, in, fl : a 2 3
      
	 a=a, i=2, u=3.000000
     Enter ch, in, fl : b 3 4.5
     
     a=b, i=3, u=4.500000
     Enter ch, in, fl : c 5 7.8
     
     a=c, i=5, u=7.800000
2.  
    Enter ch, in, fl :t 6 5.7
    
	a=t, i=6, u=5.700000
    Enter ch, in, fl :p 3 4.5
    
    a=p, i=3, u=4.500000
    Enter ch, in, fl :t 5 3.4
    
    a=t, i=5, u=3.400000

Explanation:

Step 1: The array of structures are created using the [] operator in the variable name.
Step 2: The contents are read into the structure variable using scanf() function. Each individual variables of the structure are accessed using [] and dot(.) operators i.e., structure_variable[i].variable_name.
Step 3: The contents of structure variables are prined on the output screen using printf() function .

More about arrays: Arrays
More about C Programs : C Programs