| 1. |
Define a structure. How it is different from union? Write a C program to illustrate a structure. |
|
Answer» Structures and union A structure contains an ordered group of data objects. Unlike the elements of an array, the data objects within a structure can have varied data types. Each data object in a structure is a member or field. A union is an object similar to a structure except that 1. In union, one block is used by all the member of the union but in case of structure, each member has their own memory space. All of union members start at the same location in memory. A union variable can represent the value of only one of its members at a time. 2. The size of the union is equal to the size of the largest member of the union where as size of the structure is the sum of the size of all members of the structure. For example struct book [ char name; int pages; float price; }; Now if we define struct book book 1, then it will assign 1+2+4=7 bytes of memory for book 1. If we define it as union like union book { char name; int pages; float price; }; The compiler allocates a piece of storage that is large enough to store the largest variable types in union. All three variables will share the same address and 4 bytes of memory is allocated to it. This program of structure will read name, roll no and marks in 6 subject of 3 students & then display name and roll of student who scored more than 70% marks in total. #include<stdio.h> #include<conio.h> struct student { char name[10]; int roll_no; int marks[6]; int total; int per; }; void main() { struct student stu[3]; int i,j,req; clrscr(); for(i=0;i<3;i++) { stu[i].total=0; printf("enter data for %d students :",i+1); printf("\nenter name"); scanf("%s",stu[i].name); printf("\nenter roll no "); scanf("%d",&stu[i].roll_no); printf("\nenter marks in subjects\t"); for(j=0;j<6;j++) { printf("\nenter marks in %d subject\t",j+1); scanf("%d",&stu[i].marks[j]); stu[i].total=stu[i].total+stu[i].marks[j]; } stu[i].per=stu[i].total/6; printf("\n"); } for(i=0;i<3;i++) { if(stu[i].per>70) { printf("\nSTUDENT %d",i+1); printf("\nname :"); printf("%s",stu[i].name); printf("\nroll no"); printf("%d",stu[i].roll_no); for(j=0;j<6;j++) { printf("\nmarks in %d subject\t",j+1); printf("%d",stu[i].marks[j]); } printf("\nTOTAL :%d",stu[i].total); } } getch(); } |
|