8. Write a C program to differentiate between structures and union.
#include <stdio.h>
// Definition of Structure
struct Structure {
int a;
float b;
char c;
};
// Definition of Union
union Union {
int a;
float b;
char c;
};
int main() {
// Declaring structure and union variables
struct Structure s;
union Union u;
// Assigning values to structure members
s.a = 10;
s.b = 20.5;
s.c = 'X';
// Assigning values to union members
u.a = 10; // Assigning a value to the first member (int)
// u.b = 20.5; // If you uncomment this, it will overwrite 'u.a' due to shared memory space.
//u.c = 'Y'; // Assigning a value to the third member (char)
// Printing values of the structure
printf("Structure: \n");
printf("s.a = %d, s.b = %.2f, s.c = %c\n", s.a, s.b, s.c);
// Printing values of the union
printf("Union: \n");
printf("u.a = %d, u.b = %.2f, u.c = %c\n", u.a, u.b, u.c);
// Showing the size of structure and union
printf("\nSize of Structure: %lu bytes\n", sizeof(s));
printf("Size of Union: %lu bytes\n", sizeof(u));
return 0;
}
OUTPUT: