CC
BeginnerLesson 5 of 18

Loops: for, while, do-while – C

Repetition, exit conditions, break/continue and nested loops.

for is ideal when the number of iterations is known: initialization; condition; step. while checks the condition before each iteration, do-while only afterwards (so it runs at least once).

#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 3; i++) printf("i=%d\n", i);

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

    int z;
    do { z = 10; printf("at least once: %d\n", z); } while (z < 5);

    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) continue;     // skip even numbers
        if (i > 7) break;             // end the loop
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}

Loops can be nested – for example for a small multiplication table:

#include <stdio.h>

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

You traverse arrays the classic way with an index. Use size_t (unsigned) as the counter when working with sizes – but be careful with loops that count backwards down to 0:

#include <stdio.h>

int main(void) {
    int w[] = {10, 20, 30};
    size_t n = sizeof w / sizeof w[0];
    for (size_t i = 0; i < n; i++) printf("%d ", w[i]);
    printf("\n");
    for (size_t i = n; i-- > 0; ) printf("%d ", w[i]);   // backwards, without underflow
    printf("\n");
    return 0;
}
Warningfor (size_t i = n - 1; i >= 0; i--) is an infinite loop: size_t is unsigned, i >= 0 is always true, and 0 - 1 wraps around to the largest value. Use the i-- > 0 pattern as above.
TipA loop variable declared in the for header (for (int i = ...)) exists only inside the loop. This has been allowed since C99 and is recommended.