TExcelTAD
Home › C › C For Loop

C For Loop

When you know in advance how many times something should repeat, the for loop is the tool of choice. It puts the three ingredients of a counting loop — start, condition and update — together on one line, so you can see the whole loop at a glance.

Syntax

c
for (initialisation; condition; update) {
    // body
}
  1. initialisation runs once, before anything else (int i = 0).
  2. condition is checked before each pass; the loop stops when it is false.
  3. update runs after each pass (i++).
c · try it yourself
#include <stdio.h>

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

This is exactly equivalent to the while version:

c
int i = 0;
while (i < 5) {
    printf("i = %d\n", i);
    i++;
}

A variable declared in the initialisation (C99 and later) only exists inside the loop. After the closing brace, i is gone.

Counting in different ways

The update can be any expression — count down, count in steps of two, multiply:

c · try it yourself
#include <stdio.h>

int main(void) {
    printf("Even numbers: ");
    for (int i = 0; i <= 10; i += 2) {
        printf("%d ", i);
    }
    printf("\nCountdown:    ");
    for (int i = 5; i >= 1; i--) {
        printf("%d ", i);
    }
    printf("\nPowers of 2:  ");
    for (int p = 1; p <= 256; p *= 2) {
        printf("%d ", p);
    }
    printf("\n");
    return 0;
}
Even numbers: 0 2 4 6 8 10 
Countdown:    5 4 3 2 1 
Powers of 2:  1 2 4 8 16 32 64 128 256 

Accumulating a result

Loops often build up a total. Start an accumulator variable at a neutral value (0 for sums, 1 for products) and update it every pass:

c · try it yourself
#include <stdio.h>

int main(void) {
    int sum = 0;
    for (int i = 1; i <= 100; i++) {
        sum += i;
    }
    printf("1 + 2 + ... + 100 = %d\n", sum);

    long long factorial = 1;
    for (int i = 1; i <= 15; i++) {
        factorial *= i;
    }
    printf("15! = %lld\n", factorial);
    return 0;
}
1 + 2 + ... + 100 = 5050
15! = 1307674368000

long long is used for the factorial because 15! is far bigger than an int can hold.

Nested loops

A loop inside another loop runs completely for each pass of the outer loop. This is how you work with rows and columns:

c · try it yourself
#include <stdio.h>

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

    printf("\n");
    for (int line = 1; line <= 4; line++) {
        for (int star = 0; star < line; star++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
   1   2   3   4
   2   4   6   8
   3   6   9  12
   4   8  12  16

*
**
***
****

The inner loop of the triangle uses line as its limit, so each row gets one more star than the previous one.

Flexible parts

All three parts of a for header are optional, and you can use the comma operator to handle two variables at once:

c · try it yourself
#include <stdio.h>

int main(void) {
    for (int left = 0, right = 6; left < right; left++, right--) {
        printf("left=%d right=%d\n", left, right);
    }
    return 0;
}
left=0 right=6
left=1 right=5
left=2 right=4

for (;;) { … } with all parts empty is an infinite loop; it is usually ended from inside with break (next lesson).

Common mistakes

Mistake Effect
for (int i = 0; i < 5; i++); the ; is an empty body — the block below runs once
for (int i = 0; i <= 5; i++) when you meant 5 passes runs 6 times (off-by-one)
using , instead of ; between the parts compile error
changing the loop counter inside the body hard-to-follow loops; avoid it

Tip: The idiom for (int i = 0; i < n; i++) runs exactly n times and matches array indexes 0 to n-1. Use it as your default.

Test yourself

How many times does for (int i = 2; i < 10; i += 2) run its body?

  1. 3
  2. 4
  3. 5
  4. 8

In which order do the parts of a for loop execute?

  1. condition, init, body, update
  2. init, condition, body, update, condition, …
  3. init, body, update, condition
  4. body, init, condition, update

A loop with 3 outer passes contains a loop with 4 inner passes. How many times does the inner body run in total?

  1. 7
  2. 4
  3. 12
  4. 3