Notifications

No notifications

/Phase 2

Loops (for / while / do-while)

Doing Things Many Times 🔁

A loop runs the same block of code repeatedly until a condition becomes false. C gives you three loop forms — they all do the same thing, just with different shapes.

1. for loop — when you know the count

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

Three slots inside ( ; ; ):

  • init — runs once at the start (int i = 0)
  • condition — checked before every iteration (i < 5)
  • update — runs after every iteration (i++)

2. while loop — when condition matters more than count

int n = 100;
while (n > 1) {
    n /= 2;
    printf("%d\n", n);
}

Condition checked before each run. If it starts false, loop runs 0 times.

3. do-while — guarantees at least one run

int choice;
do {
    printf("Enter 0 to quit: ");
    scanf("%d", &choice);
} while (choice != 0);

Condition checked after each run. Loop runs at least once.

Loop Control Statements

KeywordEffect
breakExit the loop immediately
continueSkip to the next iteration
returnExit the whole function

Quick Comparison

LoopCondition checkedRuns ≥ 1 time?Best for
forBeforeNoCounting (known iterations)
whileBeforeNo"Until something happens"
do-whileAfterYesMenus, input validation

On this page

Detailed Theory

Loops are how computers actually do work. Without them, you'd have to write printf("Hello"); a million times to print Hello a million times. With a loop, you write it once.

Anatomy of a for Loop

for (initialization; condition; update) {
    body;
}

Execution order:

1. init runs once 2. Check condition — if false, exit 3. Run body 4. Run update 5. Go to step 2

So for (int i = 0; i < 3; i++) printf("%d\n", i); produces:

0
1
2

The check happens before the body, so if i < 3 is false from the start, the body never runs.

All Three Slots Are Optional

for (;;) { ... }                  // infinite loop (must break out)
for (int i = 0; ; i++) { ... }    // no condition → infinite
int i = 0;
for (; i < 10; ) { i++; }         // ugly but legal — like a while

for (;;) is the idiomatic C way to write "loop forever".

while vs do-while — The Off-by-One Trap

int n = 0;
while (n > 0) {        // n is 0 → false → body NEVER runs
    printf("hi");
}

int m = 0; do { // body runs ONCE before check printf("hi"); // prints "hi" } while (m > 0); // then exits

Use do-while for things that must happen at least once: prompting the user for input, opening a menu, retrying a network call.

break vs continue

for (int i = 0; i < 10; i++) {
    if (i == 5) break;       // exits loop entirely → prints 0..4
    printf("%d ", i);
}

for (int i = 0; i < 10; i++) { if (i % 2 == 0) continue; // skips even → prints 1 3 5 7 9 printf("%d ", i); }

break only exits the innermost loop. To exit nested loops, either set a flag, restructure into a function and return, or use goto (legitimate here):

for (int i = 0; i < N; i++) {
    for (int j = 0; j < M; j++) {
        if (matrix[i][j] == target) {
            goto found;
        }
    }
}
found:
    /* ... */

The Off-by-One Bug

The most common loop bug. Should it be < or <=?

int arr[5];                 // valid indices: 0,1,2,3,4

for (int i = 0; i <= 5; i++) // ❌ runs 6 times — last iteration writes arr[5] (CRASH) arr[i] = 0;

for (int i = 0; i < 5; i++) // ✅ runs 5 times: indices 0..4 arr[i] = 0;

Rule of thumb for arrays: for (int i = 0; i < size; i++). Use <, not <=.

Infinite Loops

Easy to write by accident:

int i = 0;
while (i < 10) {
    printf("%d", i);   // forgot i++ — i stays 0 forever
}

Or by design:

while (1) {
    char c = getchar();
    if (c == 'q') break;
    process(c);
}

If your terminal looks frozen, you probably have an infinite loop. Press Ctrl+C to stop.

Loop Variable Scope (C99+)

In modern C, declaring the loop variable inside the for keeps it local:

for (int i = 0; i < 5; i++) {
    /* i visible here */
}
/* i NOT visible here — good */

Always prefer this — keeps your variables tightly scoped.

Nested Loops

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

Outer loop runs 3 times, inner runs 3 × 3 = 9 times. Used everywhere: matrices, grids, pairs.

When to Choose Which

You knowUse
Exact iteration countfor
A condition becomes false eventuallywhile
Must run at least once (menu / input)do-while
Loop forever (event loop, server)for(;;) or while(1)

Master loops and you've unlocked the ability to process data of any size.