The for Loop
Most loops that count have the same three parts: a variable created before the loop, a condition, and a change at the end of the block:
int number = 1; // start
while (number <= 5) { // condition
printf("%d\n", number);
number++; // step
}Counting like this is so common that C has a loop that puts all three parts on one line, for:
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}Both loops print the same:
1
2
3
4
5The parentheses after for hold the three parts, separated by semicolons (;):
int i = 1is the start. It creates the loop variable and runs only once, before everything else.i <= 5is the condition. It is checked before each iteration. When it's false, the loop ends.i++is the step. It runs after each iteration, when the block has finished.
So the order is: start, condition, block, step, condition, block, step, and so on. In our loop, i is 1, 1 <= 5 is true, the block prints 1, the step makes i 2, 2 <= 5 is true, the block prints 2… After printing 5, the step makes i 6, 6 <= 5 is false, and the loop ends.
The loop variable is often called i, but any name works. It exists only inside the loop. If you use i after the loop, the compiler doesn't know it:
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 3; i++) {
printf("%d\n", i);
}
printf("%d\n", i);
return 0;
}main.c:7:20: error: use of undeclared identifier 'i'
7 | printf("%d\n", i);
| ^
1 error generated.An undeclared identifier is a name the compiler doesn't know at that point. If you need the value after the loop, use a while loop with a variable created before it, as in the previous exercises. On the other hand, each loop can have its own i, because every i disappears when its loop ends.
Separate the three parts with semicolons, not commas. With commas, for (int i = 1, i <= 3, i++), the compiler gets confused and reports several errors at once. The first one, error: invalid '<=' at end of declaration; did you mean '='?, doesn't help much. When an error points at a line with for, check the semicolons first.
for or while? Use for when you know how many times the loop will run: from 1 to 10, or 7 times for the days of a week. Use while when you don't know it in advance, for example when you double a number until it is greater than 1000:
int number = 1;
int doublings = 0;
while (number <= 1000) {
number = number * 2;
doublings++;
}
printf("Doublings: %d\n", doublings);
printf("Number: %d\n", number);Doublings: 10
Number: 1024Instructions
Rewrite the while loop in the editor as a for loop with the variable i. Delete the while loop and the line that creates number. The program still prints the numbers from 1 to 5.
Change your loop so that it prints the numbers from 1 to 10, including 10.
Below it, write a second for loop, again with a variable i, that prints the squares of the numbers from 1 to 5: 1 x 1 = 1, 2 x 2 = 4 and so on up to 5 x 5 = 25, each on its own line. You can calculate the square right in printf: i * i.
Start programming for free
3/11