Step 2 of 7
for loops
Most loops count: start somewhere, stop at some point, and step each time. A for loop puts all three parts on one line, so you can see the whole plan at a glance:
for (init; condition; update) {
body
}
- init runs once, before anything else. Usually it creates the counter:
int i = 0. - condition is checked before every pass. If false, the loop ends.
- body runs.
- update runs after each pass, usually
i++. Then back to step 2.
#include <stdio.h>
int main(void) {
for (int i = 0; i < 5; i++) {
printf("%d ", i);
}
printf("\n");
for (int t = 10; t >= 0; t -= 5) {
printf("T-%d ", t);
}
printf("\n");
return 0;
}
0 1 2 3 4
T-10 T-5 T-0
Counting conventions
for (int i = 0; i < n; i++) runs exactly n times (0 through n-1). This "start at 0, stop before n" style is the standard in C, because it matches array positions, which also start at 0. If you need 1 through n, write for (int i = 1; i <= n; i++).
A counter declared in the for line only exists inside the loop. Using i after the loop is a compile error, which keeps names from leaking.
for or while?
They can do the same things. Use for when you're counting or the number of passes is known; use while when you loop until something happens (like input running out).
Your turn: read n and print the squares from 1 to n on one line, separated by spaces. For n = 4: 1 4 9 16.