Loops
Prerequisites: Switch statements
Syntax
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 5);
Example
for (int i = 1; i <= 3; i++) {
printf("Count: %d\n", i);
}
Expected output
Count: 1
Count: 2
Count: 3
A do...while always runs its body at least once, checking the
condition only afterward — useful for a menu loop that must show at
least one prompt.
Common mistakes
- Forgetting to update the loop variable, causing an infinite loop.
- Off-by-one errors when looping over an array —
i <= lengthreads one element past the end, which C will not stop you from doing (see Arrays, next).
Practice
Print the numbers 1 through 5 using a for loop.
Show solution
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}