Structure in C struct 1 Definition Using struct




![Array of struct : #include<stdio. h> struct employee{ int ID; float grade; char name[10]; Array of struct : #include<stdio. h> struct employee{ int ID; float grade; char name[10];](https://slidetodoc.com/presentation_image_h2/6038bdce688a606bc65b53bd5ca4bdcc/image-5.jpg)
- Slides: 5
Structure in C struct 1
Definition: �Using struct to define a storage containing different types. �For example it can contain int, char, float and array at the same time. �You can imagine the shape of the storage like this: struct employee int content of the struct ID float grade char name[10] int marks[5] Name of the struct 2
How to implement the last shape? � struct employee{ int ID; float grade; char name[10]; int marks[5]; } emp 1, emp 2; void main() { struct employee emp; } OR: typedef struct employee{ int ID; float grade; char name[10]; int marks[5]; }; void main() { employee emp; } 3
Example for reading and writing struct elements: #include<stdio. h> struct employee{ int ID; float grade; char name[10]; int marks[5]; } emp 1, emp 2; void main() { int i; float sum=0; struct employee emp; printf(“enter your ID: ”); scanf(“%d”, &emp. ID); printf(“enter your name: ”); scanf(“%s”, emp. name); printf(“enter your 5 marks: ”); for(i=0; i<5; i++){ scanf(“%d”, emp. marks[i]); sum = sum + emp. marks[i]; } emp. grade =sum; printf(“your ID: %dn”, emp. ID); printf(“ your name: %sn”, emp. name); printf(“your grade: %f”, emp. grade); printf(“ your 5 marks: ”); for(i=0; i<5; i++){ printf(“ n mark[%d] = %d”, emp. marks[i]); } } 4
Array of struct : #include<stdio. h> struct employee{ int ID; float grade; char name[10]; int marks[5]; } emp 1, emp 2; void main() { int i; float sum; struct employee emp[10]; for(j=0; j<10; j++){ sum=0; printf(“enter your ID: ”); scanf(“%d”, &emp[j]. ID); printf(“enter your name: ”); scanf(“%s”, emp[j]. name); printf(“enter your 5 marks: ”); for(i=0; i<5; i++){ scanf(“%d”, emp[j]. marks[i]); sum = sum + emp[j]. marks[i]; } emp[j]. grade =sum; } for(j=0; j<10; j++){ printf(“your ID: %dn”, emp[j]. ID); printf(“ your name: %sn”, emp[j]. name); printf(“your grade: %f”, emp[j]. grade); printf(“ your 5 marks: ”); for(i=0; i<5; i++){ printf(“ n mark[%d] = %d”, emp[j]. marks[i]); } } } 5