Write a C program to store student record using nested structure.
#include <stdlib.h>
#include <string.h>
struct subjects {
int s1, s2, s3, s4, s5;
float avg;
};
struct studentdb {
char name[100];
/* nested structure */
struct subjects s;
int min, max;
int rollno;
char grade;
};
/* prints student recods one after the other */
void printDataBase(struct studentdb *s, int n) {
int i;
printf("RollNo Name s1 s2 s3 s4 s5 Grade avg\n");
printf("-------------------------------------------------------------\n");
for (i = 0; i < n; i++) {
printf("%-10d%-15s", s[i].rollno, s[i].name);
printf("%5d%5d%5d%5d%5d", s[i].s.s1, s[i].s.s2, s[i].s.s3,
s[i].s.s4, s[i].s.s5);
s[i].s.avg = (float)(s[i].s.s1 + s[i].s.s2 + s[i].s.s3 +
s[i].s.s4 + s[i].s.s5) / 5;
if (s[i].s.avg > 80)
s[i].grade = 'A';
else if(s[i].s.avg > 60)
s[i].grade = 'B';
else
s[i].grade = 'C';
printf("%4c %4.2f\n", s[i].grade, s[i].s.avg);
}
}
int main() {
struct studentdb *s;
int i, n;
/* enter the number of students */
printf("Enter the number of students:");
scanf("%d", &n);
/* dynamically allocate memory to store student details */
s = (struct studentdb *)malloc(sizeof (struct studentdb) * n);
/* get the student details from the user */
printf("Enter your inputs:\n");
for (i = 0; i < n; i++) {
printf("Input for student %d:\n", i + 1);
getchar();
printf("Name:");
fgets(s[i].name, 100, stdin);
s[i].name[strlen(s[i].name) - 1] = '\0';
printf("Marks for 5 subjects:");
scanf("%d%d%d%d%d", &s[i].s.s1, &s[i].s.s2,
&s[i].s.s3, &s[i].s.s4, &s[i].s.s5);
printf("Rollno:");
scanf("%d", &s[i].rollno);
}
/* print the student details */
printDataBase(s, n);
return 0;
}
Output:
jp@jp-VirtualBox:~/cpgms/lab_pgms/09_struct_union$ ./a.out
Enter the number of students:3
Enter your inputs:
Input for student 1:
Name:Anand
Marks for 5 subjects:94 95 96 96 98
Rollno:1
Input for student 2:
Name:Bose
Marks for 5 subjects:95 96 97 98 99
Rollno:2
Input for student 3:
Name:Chandru
Marks for 5 subjects:99 97 95 100 100
Rollno:3
RollNo Name s1 s2 s3 s4 s5 Grade avg
------------------------------------------------------------------
1 Anand 94 95 96 96 98 A 95.80
2 Bose 95 96 97 98 99 A 97.00
3 Chandru 99 97 95 100 100 A 98.20
Enter the number of students:3
Enter your inputs:
Input for student 1:
Name:Anand
Marks for 5 subjects:94 95 96 96 98
Rollno:1
Input for student 2:
Name:Bose
Marks for 5 subjects:95 96 97 98 99
Rollno:2
Input for student 3:
Name:Chandru
Marks for 5 subjects:99 97 95 100 100
Rollno:3
RollNo Name s1 s2 s3 s4 s5 Grade avg
------------------------------------------------------------------
1 Anand 94 95 96 96 98 A 95.80
2 Bose 95 96 97 98 99 A 97.00
3 Chandru 99 97 95 100 100 A 98.20
No comments:
Post a Comment