The for Loop

Counting loops are so common that C has a special, compact loop for them: for.

#include <stdio.h>

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

Output

1
2
3
4
5

The brackets hold three parts, separated by ;:

PartHereMeaning
Startint i = 1Runs once, before the loop begins.
Conditioni <= 5Checked before every round. False = stop.
Stepi++Runs after every round.

Tip: i is the traditional name for a loop counter. It stands for index.

Counting down and in steps

#include <stdio.h>

int main() {
    for (int i = 5; i >= 1; i--) {
        printf("%d ", i);
    }
    printf("Lift off!\n");

    for (int i = 0; i <= 20; i += 5) {
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}

Output

5 4 3 2 1 Lift off!
0 5 10 15 20 

Adding things up

A very common pattern: make a total variable before the loop, and add to it inside:

#include <stdio.h>

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

Output

1 + 2 + ... + 100 = 5050

Repeating something n times

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= 10; i++) {
        printf("%d x %d = %d\n", n, i, n * i);
    }
    return 0;
}

Input (what the user types)

7

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

Remember: Use for when you know how many times to repeat, and while when you don't.

HOME LABS COMMUNITY DASHBOARD