Counting Down and in Steps
The step of a for loop doesn't have to be i++. A loop can count down, count by twos or by fives, or start at zero. You only change its three parts.
Counting down. Start at the highest number, continue while the variable is at least the lowest one, and decrease it with i--:
for (int i = 3; i >= 1; i--) {
printf("%d\n", i);
}
printf("Liftoff!\n");3
2
1
Liftoff!Watch the condition: it is i >= 1, “greater than or equal”. If you copy i <= 1 from a loop that counts up, the condition is false right at the start (3 <= 1), and the loop doesn't run even once. For the compiler, that's not an error: the loop simply prints nothing.
Counting in steps. To count by more than one, use += or -= in the step. This loop counts by fives:
for (int i = 0; i <= 20; i += 5) {
printf("%d\n", i);
}0
5
10
15
20The variable doesn't have to hit the limit exactly. With the condition i <= 22, the loop prints the same five numbers: after 20 comes 25, and 25 <= 22 is false.
Counting from zero. Programmers often start counting at 0. This loop runs 3 times, for i equal to 0, 1 and 2:
for (int i = 0; i < 3; i++) {
printf("Round %d\n", i);
}Round 0
Round 1
Round 2A loop for (int i = 0; i < n; i++) runs exactly n times. You'll see it very often, because in the next lesson, on arrays, counting starts at 0.
The most common mistake with for is being off by one: the loop runs one time more or one time less than it should. i < 3 stops at 2, i <= 3 at 3. If you start at 0 and write i <= 3, the loop runs 4 times: for 0, 1, 2 and 3. When you aren't sure how many times a loop runs, write down the values its variable takes and count them.
Instructions
The loop in the editor should cheer three times, but it cheers four times. Fix its condition, so that the program prints Hip hip hooray! exactly three times.
Below that loop, write a for loop that counts down from 10 to 1, each number on its own line. After the loop, print Happy New Year!.
At the end, write a loop that prints the leap years from 2004 to 2024: 2004, 2008, 2012, 2016, 2020 and 2024, each on its own line. Between 2004 and 2024, every fourth year is a leap year, so use += 4 as the step.
Start programming for free
4/11