Repeat work with a clear stopping rule
A loop needs initialization, a continuation condition and progress toward termination. Use for when the counter structure is clear, while when repetition depends on a condition, and do-while when the body must run at least once.
Counted repetition
#include
int main(void) {
int sum = 0;
for (int i = 1; i <= 5; ++i) {
sum += i;
}
printf("sum=%d\n", sum);
return 0;
} Expected output is sum=15. The sequence of i values is 1, 2, 3, 4, 5; when i becomes 6, the condition is false. The accumulation starts at zero, the identity for addition. Starting sum with an uninitialized local value makes every later result unreliable.
while and do-while
int remaining = 3;
while (remaining > 0) {
printf("%d ", remaining);
--remaining;
}
int choice = 0;
do {
puts("Menu displayed once");
} while (choice != 0);The while fragment prints 3, 2, 1. The do-while executes its body once before checking choice, even though choice is already zero. Its closing condition needs a semicolon.
break and continue
break exits the nearest enclosing loop or switch. continue skips the rest of the current iteration; in a for loop it still proceeds to the iteration expression. In a while loop, a continue can skip an update written at the bottom and accidentally create an infinite loop. Place updates so every continuing path makes progress.
Off-by-one and overflow
An array of length n has indices 0 through n-1, so traversal commonly uses i < n. That differs from counting the numbers 1 through n, which may use i <= n. Do not use an unsigned countdown condition such as i >= 0; it is always true for an unsigned value. Choose bounds that will not overflow the counter during its final update.
Nested loop trace
If an outer loop runs three times and an inner loop runs four times on each visit, the inner body runs twelve times. Trace the pair of indices on paper before writing a matrix operation. Print the outer newline after the inner loop, not inside every cell update.
Exercises and answers
- Print even values from 2 through 10. Expected: 2 4 6 8 10.
- Count how many integers from 1 through 20 are divisible by 3. Answer: 6.
- Reverse the first example to count from 5 down to 1 using a signed int.
- Explain why
while (n > 0) { puts("working"); }never ends when n begins positive: its body never changes n.