Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 135 ยท Control Flow

for Loops

Master the C for loop - how its three parts run, declaring the loop variable in the header (C99), counting up and down, nested loops and off-by-one bugs.

Most loops count something: the elements of an array, the rows of a table, the numbers from 1 to 100. You could write every counting loop with while, but then the three pieces that control it (the starting value, the test and the step) end up scattered over several lines. The for loop puts all three in one header, so a reader sees the whole plan at a glance.

for is the loop you'll write most often in C. This lesson explains exactly when each part of the header runs, how to count up, down and in steps, how nested loops work, and how to avoid the most famous loop bug of all: being off by one.

The three parts of a for loop

C
for (initialization; condition; update) {
    /* body */
}

The parts run in a fixed order:

  1. initialization runs once, before anything else.
  2. condition is checked before every iteration. If it is false (zero), the loop ends.
  3. The body runs.
  4. update runs after the body, then control goes back to step 2.

So a for loop is a while loop with its bookkeeping moved into the header. These two loops do exactly the same thing:

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

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

(The one real difference appears with continue, which in a for loop still runs the update. See break, continue and goto.)

C Watch the order of the parts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

This example is deliberately unusual: it uses the comma operator to print a line every time the condition is checked. You can see that the condition runs four times (for 1, 2, 3 and 4) while the body runs only three times. The last check, with i equal to 4, is the one that fails and ends the loop. Don't write real loops like this; it's only here to make the order visible.

Declaring the loop variable in the header

Since C99, you can declare the loop variable inside the header: for (int i = 0; ...). That variable exists only inside the loop. Once the loop ends, the name i is gone, which keeps it from leaking into the rest of the function and lets the next loop reuse the name.

In C89 code you'll still see the old style, with the variable declared at the top of the function:

C
int i;                     /* C89: declare first ... */
for (i = 0; i < 10; i++) { /* ... then use it in the loop */
    /* ... */
}
/* i is still visible here and equals 10 */

The old style is only useful when you need the counter's value after the loop, for example to know where a search stopped:

C Using the counter after the loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The search loop stops at index 3 with a break, and because i lives outside the loop, the code after it can tell whether something was found (i < count) or not (i == count). The second loop uses the C99 style, which you should prefer whenever you don't need the counter afterwards. The expression sizeof temps / sizeof temps[0] is the standard way to get the number of elements in an array; Arrays explains it.

Counting up, down and in steps

The update can be any expression, so you're not limited to i++:

C Different ways to count

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The last loop declares two variables in the initialization (they must have the same type) and updates both with the comma operator: lo++, hi--. That's handy for walking an array from both ends at once, for example to reverse it or check whether a word is a palindrome.

Be careful counting down with an unsigned type. for (unsigned i = 5; i >= 0; i--) never ends, because an unsigned value can't go below 0: after 0 it wraps around to 4294967295. GCC warns that the comparison is always true. Use a signed int, or write the condition as for (unsigned i = 5; i-- > 0; ), which tests before decrementing and visits 4, 3, 2, 1, 0.

Any part can be empty

All three parts of the header are optional; only the two semicolons are required.

  • No initialization: for (; i < n; i++) uses a variable that already exists.
  • No update: for (int i = 0; i < n; ) when the body decides how far to move.
  • No condition: for (;;) means "forever". It's the classic C spelling of an infinite loop, equivalent to while (1), and ends only through break, return or the end of the program.
C
for (;;) {
    int c = getchar();
    if (c == EOF || c == 'q') {
        break;
    }
    /* handle c */
}

Nested loops

A loop inside another loop is a nested loop. For every single iteration of the outer loop, the inner loop runs completely. If the outer loop runs 4 times and the inner loop 6 times, the inner body runs 4 ร— 6 = 24 times. Nested loops are how you walk through anything two-dimensional: tables, grids, images, game boards.

C A multiplication table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The outer loop picks a row, the inner loop prints every column of that row, and the printf("\n") after the inner loop ends the line. Field widths like %4d (from Printing Output with printf) keep the columns aligned. Change size to 9 to get a bigger table.

The inner loop's bounds can depend on the outer variable. That's how you print triangles and other patterns, a favorite exercise for practicing nested loops:

C Triangles from nested loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

In the first triangle, row 1 has one star, row 2 has two, and so on. The second one is centered: each row has height - row spaces, then 2 * row - 1 stars (1, 3, 5, 7, 9). When you design a pattern, write down for a few rows how many of each character you need, then turn that into a formula of row.

Watch the cost of nesting. Two nested loops over n items do about nยฒ steps; three do nยณ. For 1,000 items that's a million or a billion steps, which is the difference between instant and painfully slow. You'll learn to reason about this in Sorting and Searching Algorithms.

Off-by-one errors

An off-by-one error is a loop that runs one time too many or one time too few. It's so common that it has its own name, and in C it's dangerous: running one step past the end of an array reads or writes memory that doesn't belong to the array. That's undefined behavior: the program might print garbage, crash, or seem to work fine until it doesn't.

The safest habit is to use the half-open form for anything indexed from 0:

C
for (int i = 0; i < n; i++)    /* visits 0, 1, ..., n-1: exactly n times */

Start at 0, use < (not <=), and compare with the count. An array of n elements has valid indexes 0 through n - 1, so this pattern lines up perfectly. Compare the variants:

Header Values of i Iterations
for (i = 0; i < 5; i++) 0 1 2 3 4 5
for (i = 0; i <= 5; i++) 0 1 2 3 4 5 6
for (i = 1; i <= 5; i++) 1 2 3 4 5 5
for (i = 1; i < 5; i++) 1 2 3 4 4

The second row is the classic array bug: with int a[5], the last iteration touches a[5], which doesn't exist. The fence-post problem is another source of off-by-one errors: a 10-meter fence with a post every meter needs 11 posts, not 10.

C Fence posts and separators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Printing a list with commas is a fence-post problem: five numbers need four commas. The if (i > 0) test prints the separator before every element except the first, giving [3, 1, 4, 1, 5] with no trailing comma. The second loop shows when <= is right: the range 1 to 100 includes 100, so the condition is k <= 100, and the sum is 5050.

When you're unsure, test the loop on the smallest cases by hand: what happens with n = 0? With n = 1? A correct loop handles both without special code.

Common mistakes

  • A semicolon after the header: for (int i = 0; i < 5; i++); has an empty body. The braces below run once, after the loop. If they use an i declared in the header, the code doesn't even compile, because i is already out of scope.
  • Changing the loop variable inside the body: modifying i in both the header and the body makes the loop hard to follow. If you need irregular steps, use a while loop.
  • Comparing signed and unsigned: for (int i = 0; i < strlen(s); i++) compares an int with a size_t. GCC's -Wextra warns about signed/unsigned comparisons; use size_t i for sizes, as you'll see in Strings.
  • Recomputing an expensive condition: the condition runs on every iteration. i < strlen(s) rescans the whole string each time; compute the length once before the loop.
  • Floating-point counters: for (double x = 0.0; x != 1.0; x += 0.1) may never end, because 0.1 can't be stored exactly (see Floating-Point Numbers). Count with an integer and compute x = i * 0.1 instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many times does the body of for (int i = 2; i < 10; i += 3) run?

    i takes the values 2, 5 and 8. The next value, 11, fails i < 10, so the body runs 3 times.
  2. 2. In a for loop that runs its body 4 times, how many times is the condition evaluated?

    The condition is checked before every iteration and once more at the end, when it fails. Four successful checks plus one failing check make five.
  3. 3. What does this print? for (int i = 0; i < 3; i++) for (int j = 0; j < 2; j++) printf("x");

    The inner loop runs completely for each of the 3 outer iterations, printing 2 x's each time, so 3 ร— 2 = 6 x's.
  4. 4. You have int a[8];. Which loop visits every element exactly once without going out of bounds?

    Valid indexes are 0 to 7. Starting at 0 and using < 8 visits exactly those. The <= 8 and 1..8 versions touch a[8], which doesn't exist, and 1..7 skips a[0].
  5. 5. What is true about i after for (int i = 0; i < 10; i++) { } in C99 and later?

    A variable declared in the for header lives only inside the loop. To use the counter after the loop, declare it before the loop.

Summary

  • for (init; condition; update) runs init once, checks condition before every iteration, and runs update after every body.
  • Since C99 you can declare the loop variable in the header; it exists only inside the loop. Declare it before the loop if you need its value afterwards.
  • The update can count down, step by any amount, or update several variables with the comma operator.
  • All three parts are optional; for (;;) is an infinite loop.
  • In nested loops, the inner loop runs completely for each outer iteration, so the work multiplies.
  • Prefer the half-open pattern for (int i = 0; i < n; i++) for indexes, and test loops with n = 0 and n = 1 to catch off-by-one errors.

Next: break, continue and goto, the statements that let you leave a loop early, skip an iteration, or jump to cleanup code.