Codiqo

Learn C · lesson 18 of 60 · about 8 minutes

for Loops

Draw the disk bar ten characters at a time: count with for loops, and nest loops for rows and columns.

What you'll learn

  • Write a counting for loop
  • Count down and in steps
  • Nest loops for grids

A disk bar

The report prints Disk: 31% full, but a picture is quicker to read: Disk [####------]. It's always 10 characters, a # for every tenth of the disk that's used and a - for the rest. A loop that runs exactly 10 times, deciding one character each lap, is what a for loop is for.

Three parts in one line

for (start; condition; step) puts everything a counting loop needs in one place:

1. start runs once: int i = 0
2. condition is checked before every lap: i < 5
3. step runs after every lap: i++

Up, down and in steps

#include <stdio.h>

int main(void) {
    for (int i = 0; i < 3; i++) {
        printf("%d ", i);
    }
    printf("\n");
    for (int i = 10; i > 0; i -= 4) {
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}

Output

0 1 2
10 6 2

The disk bar

#include <stdio.h>

#define DISK_KIB 8192

int main(void) {
    int used = 3560;
    printf("Disk [");
    for (int i = 0; i < 10; i++) {
        if (i < used * 10 / DISK_KIB) {
            putchar('#');
        } else {
            putchar('-');
        }
    }
    printf("]\n");
    return 0;
}

Output

Disk [####------]

Tip

used * 10 / DISK_KIB is integer division, so 3560 KiB of 8192 gives 4: four # for a disk that's 43% full, and a partly used tenth doesn't count. putchar('#') prints a single character.

Loops inside loops

When one loop is inside another, the inner loop runs all its laps for every lap of the outer loop. Rows and columns are the classic example.

A small times table

#include <stdio.h>

int main(void) {
    for (int row = 1; row <= 3; row++) {
        for (int col = 1; col <= 3; col++) {
            printf("%4d", row * col);
        }
        printf("\n");
    }
    return 0;
}

Output

   1   2   3
   2   4   6
   3   6   9

Tip

%4d pads a number to 4 characters wide, which lines up columns neatly.

Now try it yourself

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