Structure having Integer Array as Member
Structure having Integer Array as Member
- Structure may contain the Array of integer as its Member.
- Let us discuss very familiar example of student , We can store name,roll,percent as structure members , but sometimes we need to store the marks of three subjects then we embed integer array of marks as structure member
Example :Structure
struct student { char sname[20]; int roll; float percent; int marks[3]; //Note Carefully }s1;
Access marks of Student s1 :
Access Subject 1 Marks : s1.marks[0] Access Subject 2 Marks : s1.marks[1] Access Subject 3 Marks : s1.marks[2]
Live Example :
#include <stdio.h> struct student { char sname[20]; int marks[3]; //Note Carefully }s1; int main() { printf("\nEnter the Name of Student : "); gets(s1.sname) printf("\nEnter the Marks in Subject 1 : "); scanf("%d",s1.marks[0]); printf("\nEnter the Marks in Subject 2 : "); scanf("%d",s1.marks[1]); printf("\nEnter the Marks in Subject 3 : "); scanf("%d",s1.marks[2]); printf("\n ---- Student Details -------- "); printf("\n Name of Student : %s",s1.sname); printf("\n Marks in Subject 1 : %d",s1.marks[0]); printf("\n Marks in Subject 2 : %d",s1.marks[1]); printf("\n Marks in Subject 3 : %d",s1.marks[2]); return 0; }
Output :
Enter the Name of Student : Pritesh Enter the Marks in Subject 1 : 90 Enter the Marks in Subject 2 : 80 Enter the Marks in Subject 3 : 89 ---- Student Details -------- Name of Student : Pritesh Marks in Subject 1 : 90 Marks in Subject 2 : 80 Marks in Subject 3 : 89
Explanation of the Code :
marks[3] array is created inside the structure then we can access individual array element from structure using structure variable. We even can use for loop to accept the values of the Array Element from Structure.