Chapter 2 — Loops
`for`, `while`, `do-while` — three ways to repeat. `break` and `continue` short-circuit a loop.
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`
for (int i = 0; i < 10; i++) {
printf("%d\n", i);
}Three parts: **init**, **condition**, **update** — all optional, separated by `;`.
2) `while`
while (cond) {
...
}Use when you don't know iteration count up front.
3) `do-while`
do {
...
} while (cond);Body runs at least once. Useful for input retry loops.
4) `break` and `continue`
| Keyword | What |
|---|---|
| `break` | Exit the **innermost** loop immediately |
| `continue` | Skip to the next iteration |
5) Nested loops
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
for (int i = 0; i < 10; i++) {
printf("%d ", i);
}
printf("\n");**Output**
0 1 2 3 4 5 6 7 8 9Key: `i < 10` produces 0..9; using `<=` would give 0..10.
Example 2 — `ex02_while.c`: sum 1..100
int sum = 0, i = 1;
while (i <= 100) {
sum += i;
i++;
}
printf("%d\n", sum);**Output**
5050Key: must update `i` inside the body — otherwise infinite loop.
Example 3 — `ex03_do_while.c`: retry input
int n;
do {
printf("Enter 1-9: ");
scanf("%d", &n);
} while (n < 1 || n > 9);
printf("got %d\n", n);**Output**
Enter 1-9: 0
Enter 1-9: 10
Enter 1-9: 5
got 5Key: body runs once first, then condition checked — perfect for validation.
Example 4 — `ex04_nested.c`: multiplication table 3×3
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%2d ", i * j);
}
printf("\n");
}**Output**
1 2 3
2 4 6
3 6 9Key: inner loop runs in full each outer iteration.
Example 5 — `ex05_break_continue.c`: skip 5, stop at 8
for (int i = 0; i < 10; i++) {
if (i == 5) continue;
if (i == 8) break;
printf("%d ", i);
}**Output**
0 1 2 3 4 6 7Key: `continue` skips one; `break` ends the loop.
Common mistakes
- **Off-by-one** — `i <= n` vs `i < n`.
- **Missing update** — forgetting `i++` → infinite loop.
- **`break` not enough** — nested loops need a flag.
- **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
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.
#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;
}
0 1 2 3 4 5 6 7 8 9#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;
}
5050#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;
}
Enter 1-9: 0
Enter 1-9: 10
Enter 1-9: 5
got 5#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;
}
1 2 3
2 4 6
3 6 9#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;
}
0 1 2 3 4 6 7📝 Exercises
Try them yourself first, then open the solution to compare.
Problem 1 (hw01.c)
Goal: Read positive integers terminated by 0, then print sum and mean.
- Filename: hw01.c
▶Toggle 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;
}
Problem 2 (hw02.c)
Goal: Read N (2-9) and print the times table for N.
- Filename: hw02.c
▶Toggle 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;
}
Problem 3 (hw03.c)
Goal: Print a star triangle for height N.
- Filename: hw03.c
▶Toggle 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;
}
All lecture materials and example code are openly available on GitHub.
View on GitHub ↗