Loops in C: for, while and do-while
How for, while and do-while loops work in C, with break, continue and the common off-by-one mistakes.
while (condition)repeats while the condition is true.for (start; condition; step)packs the counter into one line and is the usual choice for counting.do { ... } while (condition);always runs the body at least once.
break leaves the loop immediately and continue skips to the next pass.
To run a body n times, count from 0 with i < n. Writing i <= n runs once too often, which for an array means reading past its end.
Example
#include <stdio.h>
int main(void) {
for (int i = 0; i < 5; i++) {
if (i == 3) continue;
printf("%d ", i);
}
printf("\n");
int n = 3;
while (n > 0) {
printf("%d...", n);
n--;
}
printf("go!\n");
return 0;
}
Output:
0 1 2 4
3...2...1...go!