TH /TannoHubYOSHINOBU TANNO日本語 ↗
C Programming

C for loops: initialization, condition, and update

Yoshinobu Tanno / Technical note

Read the three parts of a for loop separately: what happens once at the start, when the loop continues, and what changes after each iteration.

Count from 1 to 5

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

The initialization runs once. The condition is checked before each iteration, and the update runs after the body.

Counting down

for (int i = 5; i > 0; i--) {
    printf("%d\n", i);
}

This prints 5, 4, 3, 2, 1. The condition means “continue while i is greater than zero.” Use i >= 0 to include zero. Trace the value, condition, and output on paper for the first three iterations.

Run these snippets inside main with stdio.h included, using C99 or later.

Continue reading

About the author’s research and engineering →