Codiqo

Learn C · lesson 26 of 60 · about 8 minutes

Looping over Arrays

Read the CPU load for the last 6 hours: fill an array with a loop, then loop over it again to print and count.

What you'll learn

  • Loop through an array with an index
  • Fill an array from input
  • Total, count and find the largest value

The last 6 hours

The report should show how busy the CPU was in each of the last 6 hours. The loads are typed in, oldest first, and each goes into the next box of an array, int hours[HOURS], with #define HOURS 6 giving its size a name. One for loop fills it with scanf, and another prints every hour and counts the busy ones, 75% or more.

The standard loop

for (int i = 0; i < n; i++) visits every index from 0 to n - 1. Inside the loop, a[i] is the current item. Almost every array task starts like this.

Step through the loop

#include <stdio.h>

int main(void) {
    int a[] = {3, 5, 7};
    int total = 0;
    for (int i = 0; i < 3; i++) {
        total += a[i];
    }
    printf("%d\n", total);
    return 0;
}

Output

15

Total, average and maximum

#include <stdio.h>

int main(void) {
    int temps[] = {12, 17, 9, 21, 15};
    int n = sizeof(temps) / sizeof(temps[0]);
    int total = 0;
    int max = temps[0];
    for (int i = 0; i < n; i++) {
        total += temps[i];
        if (temps[i] > max) {
            max = temps[i];
        }
    }
    printf("Total %d, average %.1f, max %d\n", total, (double)total / n, max);
    return 0;
}

Output

Total 74, average 14.8, max 21

Tip

Start max at the first item, not at 0. If every value were negative, starting at 0 would give the wrong answer.

Tip

&hours[i] is the address of one item, so scanf can store straight into the array.

Now try it yourself

This lesson is free in Codiqo, with 9 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.