C Programming • C17 baseline, standards-specific features labeled
Repeat Work with C Loops
Use for and while loops with clear progress and explicit termination conditions.
A loop needs a condition that eventually becomes false. Keep initialization, condition, and update together in a for loop when they describe one counter. Use while when termination depends on an event or input.
Example
#include <stdio.h>
int main(void) {
for (int step = 1; step <= 4; ++step) {
printf("step %d\n", step);
}
return 0;
}
What to expect
Prints step 1 through step 4, once each.
Key idea: Check the first and last iteration carefully; off-by-one errors often come from boundary conditions.