Skip to content
KALANBLON
Show contents

Chapter 5 of 6 · 20 min

The for loop

By the end of this chapter, you'll be able to

  • Write a for loop with a counter
  • Choose the bounds of a loop to avoid off-by-one errors
  • Nest two loops
  • Interrupt a loop with break, or skip to the next round with continue

Anatomy of a for loop

#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 5; i++) {
        printf("7 x %d = %d\n", i, 7 * i);
    }
    return 0;
}
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

Between the parentheses, three parts separated by semicolons:

  1. the initialisation int i = 1, run only once, at the start;
  2. the condition i <= 5, tested before each round, just like in a while;
  3. the increment i++, run at the end of each round.

It's exactly the same as this while, but more compact and harder to get wrong:

int i = 1;
while (i <= 5) {
    printf("7 x %d = %d\n", i, 7 * i);
    i++;
}

The variable i, declared in the for, only exists inside the loop.

i no longer exists after the loop. We display the total.

Step 10 of 10
Text description of the animation
  1. We add up the integers from 1 to 3.
  2. total starts at 0.
  3. The initialisation creates i and gives it 1. It only happens once.
  4. The condition is true: we run the body.
  5. total receives 0 + 1.
  6. End of the round: i++ moves i to 2, then the condition is tested again.
  7. total receives 1 + 2.
  8. Next round with i = 3: total receives 3 + 3.
  9. i becomes 4: the condition is false, the loop stops.
  10. i no longer exists after the loop. We display the total.

Nested loops

You can put one loop inside another. For each round of the outer loop, the inner loop makes all of its rounds:

#include <stdio.h>

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

break and continue

  • break leaves the loop immediately;
  • continue skips the end of the round and goes straight to the next one (in a for, the increment still runs).
#include <stdio.h>

int main(void) {
    // First multiple of 7 greater than 50
    for (int n = 51; n < 100; n++) {
        if (n % 7 == 0) {
            printf("Found: %d\n", n);
            break;
        }
    }
    // Numbers from 1 to 10 except multiples of 3
    for (int n = 1; n <= 10; n++) {
        if (n % 3 == 0) {
            continue;
        }
        printf("%d ", n);
    }
    printf("\n");
    return 0;
}
Found: 56
1 2 4 5 7 8 10 

Your turn

Worked exercise

Worked exercise: prime numbers

A number is prime if it has exactly two divisors: 1 and itself (2, 3, 5, 7, 11…). Write a program that displays all the prime numbers from 2 to 30, on one line.

Hint 1
For each n from 2 to 30, look for a divisor d between 2 and n - 1 with a nested loop.
Hint 2
Use a variable prime that starts at 1. As soon as you find a divisor, set it to 0 and leave the inner loop with break.
Show the solution and common mistakes
#include <stdio.h>

int main(void) {
    for (int n = 2; n <= 30; n++) {
        int prime = 1;
        for (int d = 2; d * d <= n; d++) {
            if (n % d == 0) {
                prime = 0;
                break;
            }
        }
        if (prime) {
            printf("%d ", n);
        }
    }
    printf("\n");
    return 0;
}
2 3 5 7 11 13 17 19 23 29 

The condition d * d <= n is an optimisation: if n has a divisor, it necessarily has one less than or equal to its square root. Testing up to n - 1 would give the same result, more slowly.

Common mistakes:

  • Declaring prime before the outer loop: once it has gone to 0, it never comes back to 1, and only the first numbers are displayed.
  • Starting d at 1: every number is divisible by 1, so none would be prime.

Summary

  1. 1for (initialisation; condition; increment) { … } gathers everything that drives the loop.
  2. 2The condition is tested before each round; the increment runs at the end of each round.
  3. 3for (int i = 0; i < n; i++) makes exactly n rounds: always check the first and last value.
  4. 4In nested loops, the inner loop makes all its rounds for each round of the outer one.
  5. 5break leaves the loop, continue moves on to the next round.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.