Qn-11.c (1295B)
1 /* Write a program to explain, how an array of stucture can you defined and accessed. */ 2 3 #include <stdio.h> 4 #include <string.h> 5 6 // 1. Defining the Structure 7 struct Student { 8 int rollNo; 9 char name[50]; 10 float marks; 11 }; 12 13 int main() { 14 int n, i; 15 16 printf("Enter the number of students: "); 17 scanf("%d", &n); 18 19 // 2. Defining an Array of Structures 20 // This creates 'n' blocks of memory, each large enough to hold a Student 21 struct Student s[n]; 22 23 // 3. Accessing members to STORE data 24 for (i = 0; i < n; i++) { 25 printf("\nEnter details for Student %d:\n", i + 1); 26 printf("Roll No: "); 27 scanf("%d", &s[i].rollNo); // Using dot (.) operator with index [i] 28 29 printf("Name: "); 30 getchar(); // To clear the newline character from buffer 31 fgets(s[i].name, sizeof(s[i].name), stdin); 32 s[i].name[strcspn(s[i].name, "\n")] = '\0'; // Safe newline removal 33 34 printf("Marks: "); 35 scanf("%f", &s[i].marks); 36 } 37 38 // 4. Accessing members to DISPLAY data 39 printf("\n--- Student Records ---\n"); 40 printf("ID\tName\t\tMarks\n"); 41 for (i = 0; i < n; i++) { 42 // Accessing using s[i].member 43 printf("%d\t%-15s\t%.2f\n", s[i].rollNo, s[i].name, s[i].marks); 44 } 45 46 return 0; 47 }