Show contents
Chapter 6 of 7 · 25 min
Project: a gradebook
By the end of this chapter, you'll be able to
- Split a problem into functions that each have a single job
- Model the data with a structure
- Read and validate input, then allocate the memory needed
- Test the program with a data set whose result you know
- Extend an existing program without breaking it
Step 1: model and split
Before writing a single line of code, we decide which data we handle and which functions we write.
- Data: a student has a name and three grades. That will be a structure
Student. The class will be an array ofStudentallocated withmalloc, because the number of students is only known at run time. - Functions:
read_studentreads and validates one student,averagecomputes their average,remarkturns an average into a comment, andbest_indexfinds the best average.mainonly orchestrates.
The input format: first the number of students, then one line per student, with a name without spaces and three grades out of 20.
main displays the report, then frees the memory.
Text description of the animation
- main first reads the number of students, checks it, then allocates the array with malloc.
- For each student, read_student fills the structure whose address it receives.
- A grade outside 0 to 20 is refused: the program frees the memory and stops cleanly.
- For the display, average computes and remark translates into a comment.
- best_index goes through the class and keeps the index of the best average.
- main displays the report, then frees the memory.
Step 2: the complete program
Read it function by function: each one is short and tests one case at a time.
#include <stdio.h>
#include <stdlib.h>
#define GRADE_COUNT 3
typedef struct {
char name[32];
double grades[GRADE_COUNT];
} Student;
// Reads one student; returns 1 if the input is valid, 0 otherwise.
int read_student(Student *s) {
if (scanf("%31s", s->name) != 1) {
return 0;
}
for (int i = 0; i < GRADE_COUNT; i++) {
if (scanf("%lf", &s->grades[i]) != 1 || s->grades[i] < 0 || s->grades[i] > 20) {
return 0;
}
}
return 1;
}
double average(const Student *s) {
double sum = 0;
for (int i = 0; i < GRADE_COUNT; i++) {
sum += s->grades[i];
}
return sum / GRADE_COUNT;
}
const char *remark(double avg) {
if (avg >= 16) return "Excellent";
if (avg >= 14) return "Very good";
if (avg >= 12) return "Good";
if (avg >= 10) return "Pass";
return "Fail";
}
int best_index(const Student students[], int n) {
int best = 0;
for (int i = 1; i < n; i++) {
if (average(&students[i]) > average(&students[best])) {
best = i;
}
}
return best;
}
int main(void) {
int n = 0;
if (scanf("%d", &n) != 1 || n <= 0 || n > 1000) {
printf("Invalid number of students\n");
return 1;
}
Student *class_list = malloc(n * sizeof *class_list);
if (class_list == NULL) {
printf("Not enough memory\n");
return 1;
}
for (int i = 0; i < n; i++) {
if (!read_student(&class_list[i])) {
printf("Invalid input for student %d\n", i + 1);
free(class_list);
return 1;
}
}
for (int i = 0; i < n; i++) {
double avg = average(&class_list[i]);
printf("%-10s %5.2f %s\n", class_list[i].name, avg, remark(avg));
}
int b = best_index(class_list, n);
printf("Best average: %s\n", class_list[b].name);
free(class_list);
return 0;
}
Three new things:
#define GRADE_COUNT 3defines a constant: before compilation, everyGRADE_COUNTis replaced by3. To switch to four grades, only one line changes.scanf("%31s", s->name)reads a word of at most 31 characters: that leaves one box for'\0'in the array of 32. Without this limit, a name that's too long would overflow the array. There's no&, becauses->nameis an array, so it's already an address.const char *remark(...)returns the address of a fixed string, written in the program, whichprintfdisplays with%s.
Step 3: test with known data
Always test with data whose result you've worked out by hand. For example, for Awa: (15 + 17 + 16.5) / 3 = 16.17, so "Excellent".
4
Awa 15 17 16.5
Kofi 9 11.5 10
Lina 12 8 9
Mateo 18 14 13
Awa 16.17 Excellent
Kofi 10.17 Pass
Lina 9.67 Fail
Mateo 15.00 Very good
Best average: Awa
Also test the error cases: a negative number of students, a grade of 25, a word instead of a grade. The program must display a clear message and stop without leaking memory.
Your turn
Worked exercise
Worked exercise: class statistics
Add two functions to the gradebook: double class_average(const Student students[], int n), which returns the average of the averages, and int pass_count(const Student students[], int n), which counts the students with at least 10. With the test data, the program must display Class average: 12.75 and Passed: 3 / 4.
To test your functions without typing the grades again, you can initialise the class directly in the code, as in the solution.
Hint 1
average function in a loop: don't recompute the sums of grades.Hint 2
{"Awa", {15, 17, 16.5}}.Show the solution and common mistakes
#include <stdio.h>
#define GRADE_COUNT 3
typedef struct {
char name[32];
double grades[GRADE_COUNT];
} Student;
double average(const Student *s) {
double sum = 0;
for (int i = 0; i < GRADE_COUNT; i++) {
sum += s->grades[i];
}
return sum / GRADE_COUNT;
}
double class_average(const Student students[], int n) {
double total = 0;
for (int i = 0; i < n; i++) {
total += average(&students[i]);
}
return total / n;
}
int pass_count(const Student students[], int n) {
int passed = 0;
for (int i = 0; i < n; i++) {
if (average(&students[i]) >= 10) {
passed++;
}
}
return passed;
}
int main(void) {
Student class_list[] = {
{"Awa", {15, 17, 16.5}},
{"Kofi", {9, 11.5, 10}},
{"Lina", {12, 8, 9}},
{"Mateo", {18, 14, 13}},
};
int n = sizeof class_list / sizeof class_list[0];
printf("Class average: %.2f\n", class_average(class_list, n));
printf("Passed: %d / %d\n", pass_count(class_list, n), n);
return 0;
}
Class average: 12.75
Passed: 3 / 4
Common mistakes:
- Dividing by
ninside the loop instead of afterwards: you get a wrong value. - Writing
average(students[i]): the function expects an address, you need&students[i]. The compiler refuses to pass a structure where it expects a pointer. - Computing
pass_countwith> 10: a student with exactly 10 would be counted as failing.
Summary
- 1Before coding, decide on the data (structures) and the functions, each with a single job.
- 2main orchestrates: it reads, validates, allocates, calls the functions, displays and frees.
- 3Limit the size of strings you read (%31s for an array of 32) and validate every input.
- 4Test with data whose result you know, then with invalid data.
- 5#define gives a name to a constant used in several places.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.