Skip to the task
Layout
Back to classic view

You are looking at lesson 3. Your place is still lesson 12, task 1: malloc.

EDITTask 10 of 22 · step 5: StatisticsStatistics
Statistics in practice/03/

At least one grade, then the lowest, the highest and how many failed.

Checklist

  • Every task is one commit with a clear message.

Numbered notes in the code explain the important lines.

Details & hint
  • Right after reading count: while (count < 1), as for a grade, so a division by 0 can no longer happen.
  • Three new variables before the loop and three ifs at the end of it.
  • lowest starts at 10 and highest at 1, so the first grade always replaces them.

Stuck? If lowest started at 0, no grade would be smaller, and the answer would always be 0.

practice 03 main.c Code Diff +18
M · MODIFIED Green = add, blue = change, red mark = removed line.
#include <stdio.h>
#include "input.h"
int main(void) {
int count = read_int("How many grades? ");
while (count < 1) {
Note 1: At least one grade: no more division by 0.
printf("At least one grade is needed.\n");
count = read_int("How many grades? ");
}
int sum = 0;
int lowest = 10;
Note 2: Starts at the largest possible: the first grade replaces it.
int highest = 1;
Note 3: Starts at the smallest possible.
int failed = 0;
for (int i = 1; i <= count; i++) {
printf("%d. ", i);
int grade = read_int("Grade: ");
while (grade < 1 || grade > 10) {
printf("Grade must be between 1 and 10.\n");
grade = read_int("Grade: ");
}
switch (grade) {
case 10:
printf("Excellent\n");
break;
case 9:
printf("Very good\n");
break;
case 8:
printf("Good\n");
break;
case 7:
printf("Fair\n");
break;
case 6:
printf("Satisfactory\n");
break;
case 5:
printf("Weak\n");
break;
default:
printf("Unsatisfactory\n");
break;
}
sum += grade;
if (grade < lowest) {
lowest = grade;
}
if (grade > highest) {
highest = grade;
}
if (grade < 5) {
failed++;
Note 4: ++ adds 1.
}
}
double average = (double)sum / count;
printf("Average: %.2f\n", average);
printf("Lowest: %d, highest: %d\n", lowest, highest);
printf("Failed: %d\n", failed);
return 0;
}