While & For Loops

While & For Loops in C: A sentry has a simple job: walk to the end of the fence, checking each post.

The Analogy: A Sentry Walking a Fence

A sentry has a simple job: walk to the end of the fence, checking each post. Three ways to give that order exist, and they differ only in when the checking happens.

"Keep walking while there are still posts ahead" is a while loop — the sentry checks before taking each step, so if the fence is zero posts long they never move at all.

"Check a post, then keep going while there are more" is a do-while loop. The sentry inspects one post no matter what, which is exactly right for showing a menu before asking whether to quit.

"For each of the 40 posts, check it" is a for loop. The count, the test and the step are stated together in one line, so a reader can see the shape of the whole walk without reading the body.

All three compile to essentially the same machine code. Choosing between them is a communication decision, not a performance one.


Syntax or Core Structure

#include <stdio.h>

int main(void) {
    /* while: test first, so it may run zero times */
    int countdown = 3;
    while (countdown > 0) {
        printf("while: %d\n", countdown);
        countdown--;
    }

    /* do-while: body first, so it always runs at least once */
    int attempts = 0;
    do {
        attempts++;
        printf("do-while: attempt %d\n", attempts);
    } while (attempts < 2);

    /* for: setup, test and step, all visible in the header */
    for (int i = 0; i < 3; i++) {
        printf("for: i = %d\n", i);
    }

    return 0;
}

Output:

while: 3
while: 2
while: 1
do-while: attempt 1
do-while: attempt 2
for: i = 0
for: i = 1
for: i = 2

Note the semicolon after while (attempts < 2) in the do-while. It is required there, and forbidden after a plain while header.

The three slots of a for header

for (initialisation; condition; step) {
    body
}

Each slot is optional. Leave all three empty and you have C's canonical infinite loop, for (;;). The header is exactly equivalent to this while:

{
    initialisation;
    while (condition) {
        body
        step;
    }
}

That equivalence explains something people find odd: the step runs after the body, not before the next test in some separate phase. It also explains why declaring the counter inside the header (for (int i = 0; ...), legal since C99) keeps i invisible outside the loop — the whole thing behaves as if wrapped in braces.

LoopTest happensRuns at least onceReach for it when
whilebefore the bodynoyou are waiting for a condition to change
do-whileafter the bodyyesa menu, a prompt, or any retry that must happen once
forbefore the bodynothe count is known, or there is one obvious counter

Technical Depth: Bounds, Counters and Hidden Costs

Write half-open ranges

The C convention is for (int i = 0; i < n; i++): start at zero, stop before n. This is not arbitrary. The loop runs exactly n times, i matches the valid array indices 0 through n - 1, and the count of iterations is simply n - 0. Every <= in a loop condition deserves a second look, because i <= n with an array of size n reads one element past the end.

Counting down with an unsigned type

This loop never terminates:

for (unsigned int i = n - 1; i >= 0; i--) { /* ... */ }

An unsigned value is never negative, so i >= 0 is always true. When i is 0 and the step runs, it wraps to 4294967295 and the loop carries on into memory it does not own. Two safe forms:

for (unsigned int i = n; i-- > 0; )  { /* i takes n-1 down to 0 */ }
for (size_t i = n; i > 0; i--)       { use(array[i - 1]); }

Also worth knowing: n - 1 when n is an unsigned zero is already 4294967295 before the loop even starts.

Do not put work in the condition

for (size_t i = 0; i < strlen(s); i++)   /* strlen runs every iteration */

The condition is re-evaluated on every pass, so this walks the string once per character and turns a linear loop into a quadratic one. Hoist it:

size_t len = strlen(s);
for (size_t i = 0; i < len; i++)          /* linear again */

Never count with a floating-point variable

for (double x = 0.0; x != 1.0; x += 0.1) does not terminate, because 0.1 is not exactly representable and the accumulated sum never equals 1.0 exactly. Count with an integer and derive the value: for (int i = 0; i < 10; i++) { double x = i * 0.1; }.

Nested loops multiply

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

Output:

   1   2   3   4   5
   2   4   6   8  10
   3   6   9  12  15
   4   8  12  16  20
   5  10  15  20  25

The inner loop runs to completion for every single pass of the outer one, so the body executes 25 times. Two nested loops over the same n items is n squared work — fine for 5, catastrophic for 100000. Use distinct, meaningful counter names (row and col, not i and j) so a swap becomes obvious rather than invisible.


Real World Example: Reading Until the Input Runs Out

Command-line tools rarely know in advance how much data is coming. The idiomatic C answer is to loop on the return value of the read, which handles both a clean end of input and malformed data with one condition.

#include <stdio.h>

int main(void) {
    double value = 0.0, sum = 0.0, min = 0.0, max = 0.0;
    long count = 0;

    printf("Enter numbers, then Ctrl+D (Ctrl+Z on Windows):\n");

    while (scanf("%lf", &value) == 1) {
        if (count == 0) {
            min = max = value;
        } else if (value < min) {
            min = value;
        } else if (value > max) {
            max = value;
        }
        sum += value;
        count++;
    }

    if (count == 0) {
        printf("No numbers read.\n");
        return 1;
    }

    printf("count = %ld\n", count);
    printf("sum   = %.2f\n", sum);
    printf("mean  = %.2f\n", sum / count);
    printf("min   = %.2f\n", min);
    printf("max   = %.2f\n", max);
    return 0;
}

Output:

Enter numbers, then Ctrl+D (Ctrl+Z on Windows):
4 8 15 16 23 42
count = 6
sum   = 108.00
mean  = 18.00
min   = 4.00
max   = 42.00

Three habits are on display. The loop condition is == 1, meaning "one item was converted successfully" — anything else, including end of input, stops the loop. min and max are seeded from the first value rather than from 0 or some guessed sentinel, so a set of all-negative numbers still works. And the empty case is handled explicitly, because sum / count with count at zero is undefined behaviour, not nan.


Common Mistakes

  1. A stray semicolon after the header. for (int i = 0; i < n; i++); has an empty body, so the block below it runs once with i already finished.
  2. Off-by-one with <=. for (i = 0; i <= n; i++) sum += a[i]; reads one element past the array. Use < with the size.
  3. Counting down with an unsigned type. i >= 0 is always true for unsigned i, so the loop wraps around instead of ending.
  4. Forgetting to change the loop variable. A while whose body never touches the condition variable runs forever. for protects you here, which is a reason to prefer it when there is a counter.
  5. Modifying the counter inside the body as well as the header. The loop then advances by two, or by an amount that depends on a branch. Change it in one place only.
  6. Calling strlen or any other O(n) function in the condition. It re-runs every iteration. Hoist it into a variable first.
  7. Looping with a floating-point counter. Accumulated rounding means x != 1.0 may never be satisfied. Count with integers.
  8. Declaring the counter outside the loop out of habit. for (int i = ...) keeps i local, which stops a later loop from accidentally depending on the previous one's final value.

Best Practices

  • Use for when there is a counter or a known number of passes, while when you are waiting on a condition, and do-while when the body must run at least once.
  • Prefer the half-open form 0 up to but not including n. It makes the iteration count obvious and matches array indices exactly.
  • Declare the counter in the header, and use size_t for anything that indexes an array or holds a length.
  • Hoist any invariant computation out of the condition and out of the body.
  • Name nested counters after what they mean — row, col, byte, attempt — rather than i, j, k.
  • Keep loop bodies short. Once a body passes about 20 lines, move its work into a function and let the loop read as a single sentence.
  • Write for (;;) rather than while (1) for a deliberate infinite loop; it signals intent and never triggers a "condition is constant" warning.
  • State the loop invariant in a comment when the logic is subtle. "At the top of each pass, sum holds the total of the first i elements" prevents more bugs than any amount of testing.

Practice Exercises

  1. Three shapes, one job. Print the numbers 1 to 10 three times, once with each loop form. Then rewrite the for version as its exact while equivalent and confirm the output is byte-for-byte identical.
  2. Digit surgery. Read a positive integer and, using a while loop with % and /, print the number of digits, the sum of the digits, and the number reversed. Verify that 9305 gives 4 digits, a digit sum of 17, and reverses to 5039.
  3. A retry prompt. Use a do-while to ask for a number between 1 and 100, re-prompting until the input is valid. Handle non-numeric input too, remembering that a failed scanf leaves the bad characters in the buffer and you must consume them or loop forever.
  4. The quadratic trap, measured. Write a loop over a long string that calls strlen in its condition, and a second that hoists the length out. Time both on a string of 100000 characters and report the ratio. Explain in one sentence why the ratio grows as the string gets longer.