Write a C program to add two distances (in inch-feet system) using Structures Structure name is Distance Two members – feet as integer, inch as float Three structure variables - d1,d2,result Get d1 and d2 from the user. Then add and get the result Convert inches to feet if it is greater than or equal to 12 Print the final result
Union Only store information in one field at any one time When a new value is assigned to a field, existing data is replaced with the new data. Thus unions are used to save memory. They are useful for applications that involve multiple members, where values need not be assigned to all the members at any one time.
Declaration & initialization of union Like structures, an union can be declared with the keyword union union student { int marks; char gender; }; To access the members of the union, use the dot operator (.)
Declaration & initialization of union Unlike structures, initialization cannot be done to all members together. #include < stdio.h > typedef struct point1 { int x,y ; }; typedef union point2 { int x; int y; }; main() { point1 p1={2,3}; // point p2={4,5}; illegal with union point2 p2; p2.x=4; p2.y=5; printf (“The coordinates of p1 are % and %d”, p1.x,p1.y); printf (“The coordinates of p2 are % and %d”, p2.x,p2.y); }
Wrong output Output The coordinated of p1 are 2 and 3 The coordinated of p2 are 5 and 5
//Corrected program #include < stdio.h > struct point1 { int x,y ; }; union point2 { int x,y ; }; main() { struct point1 p1={2,3}; // point p2={4,5}; illegal with union union point2 p2; p2.x=4; printf ("The coordinates of p1 are %d and %d \n", p1.x,p1.y); printf ("The x coordinates of p2 is %d \n", p2.x); p2.y=5; printf ("The y coordinates of p2 is %d", p2.y); }
Correct output Output: The coordinates of p1 are 2 and 3 The x coordinates of p2 are 4 The y coordinates of p2 are 5
Another example #include < stdio.h > #include < string.h > union Data { int i ; float f; char str[20]; }; int main( ) { union Data data ; data.i = 10; printf ( " data.i : %d\n", data.i ); data.f = 220.5; printf ( " data.f : %f\n", data.f ); strcpy ( data.str , "C Programming"); printf ( " data.str : %s\n", data.str ); return 0; }