Let's build a real program that uses almost everything from this course. It reads a class of students and their marks, then prints a neat report.
The plan
- A
structholds one student: name, three marks, and the average. - A function works out the average.
- A function turns an average into a grade letter.
mainreads the data, then prints a table and the top student.
The program
#include <stdio.h>
typedef struct {
char name[20];
int marks[3];
double average;
} Student;
double averageOf(int *marks, int count) {
int total = 0;
for (int i = 0; i < count; i++) {
total += marks[i];
}
return (double) total / count;
}
char gradeFor(double avg) {
if (avg >= 90) {
return 'A';
} else if (avg >= 75) {
return 'B';
} else if (avg >= 50) {
return 'C';
}
return 'F';
}
int main() {
int n;
Student cls[30];
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%s %d %d %d", cls[i].name, &cls[i].marks[0], &cls[i].marks[1], &cls[i].marks[2]);
cls[i].average = averageOf(cls[i].marks, 3);
}
printf("%-10s %7s %s\n", "Name", "Average", "Grade");
int top = 0;
for (int i = 0; i < n; i++) {
printf("%-10s %7.1f %c\n", cls[i].name, cls[i].average, gradeFor(cls[i].average));
if (cls[i].average > cls[top].average) {
top = i;
}
}
printf("Top student: %s\n", cls[top].name);
return 0;
}Input (what the user types)
4 Asha 92 88 95 Ben 70 65 80 Cara 45 50 40 Dev 85 90 78
Output
Name Average Grade Asha 91.7 A Ben 71.7 C Cara 45.0 F Dev 84.3 B Top student: Asha
What to notice
- Each function does one small job and has a clear name.
cls[i].marksis an array inside a struct inside an array – and it all still works with[ ]and..%-10sand%7.1fline the table up.
Tip: Try changing it: add a fourth mark, or print how many students got each grade.