Codiqo

Learn C · lesson 28 of 60 · about 10 minutes

Project: Backup Statistics

Report on past backups: read sizes into an array until 0, never past its end, and print the total, the biggest and the average.

What you'll learn

  • Fill an array from input
  • Stop before the array is full
  • Report statistics neatly

Past backups

The last part of this report looks at past backups. Their sizes are typed in, newest first, until a 0, and go into int sizes[MAX_BACKUPS]. The array has room for 7, so the loop stops at 7 even if more are typed: C would happily write past the end. Then the report gives the total, the biggest (with index_of_max from the last lesson) and the average, and says whether a backup of the average size should fit in the free space.

The plan

1. Read sizes into the array while there's room and the size isn't 0, counting them in n
2. If n is 0, there's nothing to report
3. Otherwise total the first n items, find the biggest and work out the average
4. Compare the average with the free space

Score statistics

#include <stdio.h>

#define MAX_SCORES 20

double average(const int a[], int n) {
    int total = 0;
    for (int i = 0; i < n; i++) total += a[i];
    return (double)total / n;
}

int highest(const int a[], int n) {
    int best = a[0];
    for (int i = 1; i < n; i++) if (a[i] > best) best = a[i];
    return best;
}

int lowest(const int a[], int n) {
    int worst = a[0];
    for (int i = 1; i < n; i++) if (a[i] < worst) worst = a[i];
    return worst;
}

int main(void) {
    int scores[MAX_SCORES];
    int n;
    scanf("%d", &n);
    if (n < 1 || n > MAX_SCORES) {
        printf("Need 1 to %d scores\n", MAX_SCORES);
        return 1;
    }
    int passes = 0;
    for (int i = 0; i < n; i++) {
        scanf("%d", &scores[i]);
        if (scores[i] >= 50) passes++;
    }
    printf("Scores:    %d\n", n);
    printf("Average:   %.1f\n", average(scores, n));
    printf("High/Low:  %d/%d\n", highest(scores, n), lowest(scores, n));
    printf("Pass rate: %d%%\n", passes * 100 / n);
    return 0;
}

Output

Scores:    5
Average:   61.2
High/Low:  90/38
Pass rate: 60%

Tip

scanf returns how many values it read, so scanf("%d", &size) == 1 is false when the input runs out, and the loop stops even without a 0.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.