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
1int count = 0;23while (count < 5) {4printf("%d\n", count);5count++;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
1int input;23do {4printf("Enter a positive number: ");5scanf("%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
1for (int i = 0; i < 5; i++) {2printf("%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
1for (int i = 0; i < 10; i++) {2if (i == 3) continue; // skip this iteration3if (i == 7) break; // exit the loop entirely4printf("%d\n", i);5}6// prints: 0 1 2 4 5 6
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:1int i = 0;2while (i < 10) {3printf("%d\n", i);4// forgot i++ — this never terminates5}
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:
1for (int row = 0; row < 3; row++) {2for (int col = 0; col < 3; col++) {3printf("(%d,%d) ", row, col);4}5printf("\n");6}