Array of Unions


  • Till now we have seen array of basic data types like array of int ,array of float ,array character etc.
  • But now we will see how to make array of Unions variable.
  • So,let's define a Union
Let's define a Union Student with name ,rollno,div as it's attribute.

Definition:
union student  //union name
{
    int  rollno; //member1 ,integer variable which will store,
                 //student roll no.
                 
    char  name[20]; //member2 a character array of 20 character
                    //which will store name of student.
                    
    char  div;  //member3 a character variable,
              //which will store division of student.
};

Syntax:Declaration of array of union
union  union_name   union_variable_name[size_of_array];

Declaration of array of union student
void main()
{
//declaration of student array.
union student s[10];

}

How to Access members of union array.

  • As,you know every array element has an unique index number,Which starts from 0 index.
  • Means first array element wil have index 0,second array element will have index 1 and So on...

Syntax | Accessing member of union array
union_variable_name[index_number].member_name;

Let's see syntax of accessing the members of student array.

Syntax of Accessing: Rollno of array student
  array_name[index_number].rollno;

Syntax of Accessing: Name of array student
  array_name[index_number].name;

Syntax of Accessing: Div of array student
  array_name[index_number].div;

  • This is how we access the member of union array.



Now , we will see program of taking members of union as Input.

Taking Input:
void main()
{
int i;
//declaration of student array.
union student s[3];

for(i=0; i<3 ;i++)
{
    printf("\nEnter name of student: ");
    gets(s[i].name);//taking name of student
    printf("\nEnter the student roll no:");
    scanf("%d",&s[i].rollno);//taking student rollno
    printf("\nstudent division:");
    scanf("%c",s[i].div);//taking student division
}
}

Output:
Enter name of student: Roy
Enter the student roll no: 1
student division: A

Enter name of student: Jason
Enter the student roll no: 2
student division: B

Enter name of student: Tom
Enter the student roll no: 3
student division: A

Printing the student data:
int i;
for(i=0; i<3 ;i++)
{
printf("\nstudent roll no and Name is  %d and %s and studies in %c division",s[i].rollno,s[i].name,s[i].div);
   
}

Output:

student roll no and Name is 1 and Roy and studies in A division
student roll no and Name is 2 and Jason and studies in B division
student roll no and Name is 3 and Tom and studies in A division





  • See the below image of array of Union student



    • This how we can take members of union as input from User.
    • This how we can work with array of union In C.






    Related Concept:



    People Also Searched: