Skip to content
FollowtheDamnCode

The for Loop

Repeat a set number of times.

5 minute read

Big idea

A for loop puts start, check, and change on one line — perfect when you know how many times to repeat.

The idea

for (start; check; change) {
    // body
}
for (int i = 1; i <= 5; i++) {
    printf("%d\n", i);
}
  1. int i = 1 — runs once, before anything else.
  2. i <= 5 — checked before each round; false ends the loop.
  3. i++ — runs after each round (i++ means "add 1 to i" — next lesson).

It's exactly the while loop from before, folded into one line:

int i = 1;            // start
while (i <= 5) {      // check
    printf("%d\n", i);
    i++;              // change
}

Try it

The 7 times table — change 7 to any number
#include <stdio.h>

int main(void) {
    int n = 7;
    for (int i = 1; i <= 10; i++) {
        printf("%d x %d = %d\n", n, i, n * i);
    }
    return 0;
}
output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

Run and edit it in the app.

Adding things up

A loop plus a running total is one of the most common patterns in programming:

Predict: sum of 1 to 100
#include <stdio.h>

int main(void) {
    int sum = 0;
    for (int i = 1; i <= 100; i++) {
        sum = sum + i;
    }
    printf("%d\n", sum);
    return 0;
}
What does it print? Show the answer
5050

Run and edit it in the app.

The loop can count any way you like: for (int i = 10; i >= 1; i--) counts down, and for (int i = 0; i <= 20; i += 5) goes 0, 5, 10, 15, 20.

Off by one

i < 5 and i <= 5 differ by exactly one round. Starting at 0 and using < is the C habit, because arrays (coming soon) count from 0:

Fix the bug: print exactly 5 stars
#include <stdio.h>

int main(void) {
    for (int i = 0; i <= 5; i++) {
        printf("*");
    }
    printf("\n");
    return 0;
}
output
*****

Run and edit it in the app.

Watch it

Think of it like

Doing 10 push-ups: you start at 1, check "am I at 10 yet?", and count one more after each push-up.

🕷️ Spidey-sense: for (int floor = 1; floor <= 102; floor++) climb(); — the Empire State Building, one floor at a time. I always know exactly how many are left.

Key terms

  • for loop — A loop with start, check, and change in its header.
  • Loop variable — The counter the loop uses, like i.
  • Off-by-one error — Running one round too many or too few.

Check yourself

In for (A; B; C) which part runs only once?

How many times does for (int i = 0; i < 5; i++) run?

What does for (int i = 10; i >= 0; i -= 5) visit?