$ overview
overview/0x05·Control Flow

Loops

Repetition with while, do-while, and for, plus break and continue.

C gives you three loop constructs. They're interchangeable in power — anything you can write with one, you can write with another — but each communicates a different intent to the reader.

while: repeat while a condition holds

while.c
1int count = 0;
2 
3while (count < 5) {
4 printf("%d\n", count);
5 count++;
6}

The condition is checked before each iteration. If it's false the first time, the body never runs at all.

do-while: run at least once

do-while.c
1int input;
2 
3do {
4 printf("Enter a positive number: ");
5 scanf("%d", &input);
6} while (input <= 0);

The condition is checked after the body, so it always runs at least once — a natural fit for input validation, where you need to ask before you can check the answer.

for: repeat a known number of times

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

The three parts of a for loop are init, condition, and update — run once, checked before every iteration, and run after every iteration, respectively. It's the standard choice whenever you're counting or walking through a fixed range, like the indices of an array.

break and continue

break-continue.c
1for (int i = 0; i < 10; i++) {
2 if (i == 3) continue; // skip this iteration
3 if (i == 7) break; // exit the loop entirely
4 printf("%d\n", i);
5}
6// prints: 0 1 2 4 5 6
warning: Watch for infinite loops
A while or for loop whose condition never becomes false will run forever. This usually happens from forgetting to update the loop variable, or updating the wrong one:
infinite.c
1int i = 0;
2while (i < 10) {
3 printf("%d\n", i);
4 // forgot i++ — this never terminates
5}

Nested loops

Loops can contain other loops — common for working through a grid or table. break and continue only affect the innermost loop they're written in:

nested.c
1for (int row = 0; row < 3; row++) {
2 for (int col = 0; col < 3; col++) {
3 printf("(%d,%d) ", row, col);
4 }
5 printf("\n");
6}