| Form | Use when |
|---|---|
while | Zero or more times; the condition is not a simple counter |
do-while | Must run once (read until valid) |
for | Index + bound + step live together |
Mental model: write the loop so a reader can answer: first state, stop condition, what changes so it can stop. C has no enhanced-for.
while ((c = getchar()) != EOF) {
putchar(c);
}
int n;
do {
n = read_n();
} while (n < 0);
do-while needs the trailing semicolon.for (int i = 0; i < n; i++) { /* C99: declaration in for */
use(a[i]);
}
int i; before the loop. Wave A uses C99 loop-scope i.i <= n when indexes are 0 .. n-1.for (;;) is an infinite loop. Exit with break or return.size_t: for (size_t i = n; i-- > 0; ) is a known idiom. i >= 0 is always true./* Incorrect unsigned countdown */
size_t i;
for (i = n - 1; i >= 0; i--) { } /* wraps forever if size_t */
/* Correct */
for (size_t i = 0; i < n; i++) {
use(a[n - 1 - i]);
}
break leaves the innermost switch or loop. There are no labels in Wave A’s recommended style (C has goto instead of Java’s labeled break).continue skips the rest of the body; in a for, the update still runs.A nest is O(n × m) if both bounds grow. Name indexes r/c or i/j. Do not reuse i in the inner loop.
'\0').for (int i = 0; i < n; i--) after a copy-paste of the update.< n, not <= n, for 0-based arrays of length n.>= 0.~ Good luck with your revision! ~