Code
Grades with functions
Take topic 3's grade program and split it into functions. The program does exactly the same, but main now reads like the algorithm.
Create practice/05:
add_executable(p05_grades main.c)
target_link_libraries(p05_grades PRIVATE course_input)
main.c has three functions above main:
int is_valid(int grade)is a yes/no question: it returns 1 if the grade is from 1 to 10, else 0. The whole function is onereturnline, because a comparison already is 1 or 0.int read_grade(void)is topic 3'swhilethat asks again. Its condition now reads as words:while (!is_valid(grade)).void print_in_words(int grade)is the sameswitch. It returns nothing, it only prints, so it isvoid.
main stays short: how many grades, the loop, the average. Inside the loop there are only three lines: read, write it in words, add to the sum.
Run it
File → Reload CMake Project, pick p05_grades and ▶. Type 3, then 9, 11, 4, 10:
How many grades? 3
1. Grade: 9
Very good
2. Grade: 11
Grade must be between 1 and 10.
Grade: 4
Unsatisfactory
3. Grade: 10
Excellent
Average: 7.67
Exactly as in topic 3. Restructuring that doesn't change the behaviour is called refactoring.
Commit: Split grades into functions.