Example : A Union Program Examples in C to store values in a union and display them.
#include<stdio.h>
#include<string.h>
#include<conio.h>
 
union student 
{
    char sname[20];
    char subject[20];
    float percentage;
}; 
void main() 
{
    union student stu;    
    
       strcpy(stu.sname,"Suman");
       strcpy(stu.subject,"Computer");
       stu.percentage = 34.10;
 
       printf("Values of Union of students are :\n");
       printf(" \nStudent Name is : %s ", stu.sname);
       printf(" \nSubject is : %s ", stu.subject);
       printf(" \n\nPercentage marks is: %f ", stu.percentage); 
    
       getch();
}
Example : A Union Program Examples in C to find out the size of the union and display them.
#include <stdio.h>

union Student 
{
    int rollno;
    float fee;
    char sname[30];
};

int main() 
{
    union Student x;
    printf("Size of Student union : %d bytes", sizeof(x));  // Output will be the size of the largest member
    return 0;
}

Output: Size of Student union : 32 bytes(30 bytes of 'sname' data member + 2 bytes extra for indexing)

Loading

Categories: C

0 Comments

Leave a Reply

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.