← Back to C series
⚙️
Intermediate
for · while · do-while · break/continue

Chapter 2 — Loops

`for`, `while`, `do-while` — three ways to repeat. `break` and `continue` short-circuit a loop.

forwhilebreak
Duration
1-2 hours
Level
📊 Beginner+
Prerequisite
🎯 Intermediate 1
Outcome
Loop, exit early, skip iterations

What you'll learn

  • 1Pick the right loop shape for the job.
  • 2Use `break` to exit early and `continue` to skip a step.
  • 3Avoid common off-by-one bugs.

Core Concepts

1) `for`

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

Three parts: **init**, **condition**, **update** — all optional, separated by `;`.

2) `while`

c
while (cond) {
    ...
}

Use when you don't know iteration count up front.

3) `do-while`

c
do {
    ...
} while (cond);

Body runs at least once. Useful for input retry loops.

4) `break` and `continue`

KeywordWhat
`break`Exit the **innermost** loop immediately
`continue`Skip to the next iteration

5) Nested loops

c
for (int i = 0; i < 3; i++)
    for (int j = 0; j < 3; j++)
        printf("(%d,%d) ", i, j);

`break` exits only one level — use a flag or `goto end;` (rare) to exit all.

Examples

Example 1 — `ex01_for.c`: count 0..9

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

**Output**

text
0 1 2 3 4 5 6 7 8 9

Key: `i < 10` produces 0..9; using `<=` would give 0..10.

Example 2 — `ex02_while.c`: sum 1..100

c
int sum = 0, i = 1;
while (i <= 100) {
    sum += i;
    i++;
}
printf("%d\n", sum);

**Output**

text
5050

Key: must update `i` inside the body — otherwise infinite loop.

Example 3 — `ex03_do_while.c`: retry input

c
int n;
do {
    printf("Enter 1-9: ");
    scanf("%d", &n);
} while (n < 1 || n > 9);
printf("got %d\n", n);

**Output**

text
Enter 1-9: 0
Enter 1-9: 10
Enter 1-9: 5
got 5

Key: body runs once first, then condition checked — perfect for validation.

Example 4 — `ex04_nested.c`: multiplication table 3×3

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

**Output**

text
 1  2  3
 2  4  6
 3  6  9

Key: inner loop runs in full each outer iteration.

Example 5 — `ex05_break_continue.c`: skip 5, stop at 8

c
for (int i = 0; i < 10; i++) {
    if (i == 5) continue;
    if (i == 8) break;
    printf("%d ", i);
}

**Output**

text
0 1 2 3 4 6 7

Key: `continue` skips one; `break` ends the loop.

Common mistakes

  1. **Off-by-one** — `i <= n` vs `i < n`.
  2. **Missing update** — forgetting `i++` → infinite loop.
  3. **`break` not enough** — nested loops need a flag.
  4. **Modifying the counter in the body** — confusing and error-prone.

Recap

  • Use `for` when you know how many; `while` otherwise; `do-while` for "at least once".
  • `break` exits the innermost loop only.
  • Watch boundaries — most bugs hide there.

Try it

bash
cd src
gcc -std=c11 -Wall -o ex01 ex01_for.c && ./ex01
gcc -std=c11 -Wall -o ex02 ex02_while.c && ./ex02
gcc -std=c11 -Wall -o ex03 ex03_do_while.c && ./ex03 <<< "0\n10\n5\n"
gcc -std=c11 -Wall -o ex04 ex04_nested.c && ./ex04
gcc -std=c11 -Wall -o ex05 ex05_break_continue.c && ./ex05

💻 Examples

Compilable, runnable examples — see the output yourself.

ex01_for.ccount 0..9
CODE
#include <stdio.h>

int main(void) {
    int n;
    printf("Enter N: ");
    scanf("%d", &n);

    long sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += i;
    }
    printf("sum 1..%d = %ld\n", n, sum);
    return 0;
}
▶ Output
0 1 2 3 4 5 6 7 8 9
ex02_while.csum 1..100
CODE
#include <stdio.h>

int main(void) {
    int n;
    printf("Enter int: ");
    scanf("%d", &n);

    int original = n;
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }

    printf("%d  : %d\n", original, sum);
    return 0;
}
▶ Output
5050
ex03_do_while.cretry input
CODE
#include <stdio.h>

int main(void) {
    int choice;
    do {
        printf("\n=== Menu ===\n");
        printf("1. Greet\n");
        printf("2. Time\n");
        printf("0. Quit\n");
        printf("Choice: ");
        if (scanf("%d", &choice) != 1) break;

        switch (choice) {
            case 1: printf("Hello!\n"); break;
            case 2: printf("Study time now.\n"); break;
            case 0: printf("Bye.\n"); break;
            default: printf("Invalid choice\n");
        }
    } while (choice != 0);

    return 0;
}
▶ Output
Enter 1-9: 0
Enter 1-9: 10
Enter 1-9: 5
got 5
ex04_nested.cmultiplication table 3×3
CODE
#include <stdio.h>

int main(void) {
    for (int i = 2; i <= 9; i++) {
        printf("=== %d ===\n", i);
        for (int j = 1; j <= 9; j++) {
            printf("%d x %d = %2d\n", i, j, i * j);
        }
    }
    return 0;
}
▶ Output
 1  2  3
 2  4  6
 3  6  9
ex05_break_continue.cskip 5, stop at 8
CODE
#include <stdio.h>

int main(void) {
    /* 1~20  even  14   */
    for (int i = 1; i <= 20; i++) {
        if (i % 2 != 0) continue;   // odd 
        if (i == 14)    break;      // 14 
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}
▶ Output
0 1 2 3 4 6 7

📝 Exercises

Try them yourself first, then open the solution to compare.

Exercise 1

Problem 1 (hw01.c)

Goal: Read positive integers terminated by 0, then print sum and mean.

Requirements
  • Filename: hw01.c
Toggle solution
SOLUTION
#include <stdio.h>

int main(void) {
    int n;
    printf("Enter N: ");
    scanf("%d", &n);

    long long fact = 1;
    for (int i = 2; i <= n; i++) {
        fact *= i;
    }
    printf("%d! = %lld\n", n, fact);
    return 0;
}
Exercise 2

Problem 2 (hw02.c)

Goal: Read N (2-9) and print the times table for N.

Requirements
  • Filename: hw02.c
Toggle solution
SOLUTION
#include <stdio.h>

int main(void) {
    int n;
    printf("Enter N: ");
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) {
        for (int j = 0; j < i; j++) putchar('*');
        putchar('\n');
    }
    return 0;
}
Exercise 3

Problem 3 (hw03.c)

Goal: Print a star triangle for height N.

Requirements
  • Filename: hw03.c
Toggle solution
SOLUTION
#include <stdio.h>

int main(void) {
    for (int n = 2; n <= 100; n++) {
        int prime = 1;
        for (int d = 2; d * d <= n; d++) {
            if (n % d == 0) { prime = 0; break; }
        }
        if (prime) printf("%d ", n);
    }
    putchar('\n');
    return 0;
}
Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub ↗