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
std::cout << number << std::endl;
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++) {
std::cout << i << std::endl;
}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 print i after the loop, Clang reports error: use of undeclared identifier 'i'. On the other hand, each loop can have its own i.
Counting down and in steps. To count 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--) {
std::cout << i << std::endl;
}
std::cout << "Liftoff!" << std::endl;3
2
1
Liftoff!To count by more than one, use += or -= in the step. This loop counts by fives:
for (int i = 0; i <= 20; i += 5) {
std::cout << i << std::endl;
}0
5
10
15
20Watch the condition: i < 5 stops at 4, i <= 5 at 5. Being off by one is the most common mistake with for. And separate the three parts with semicolons, not commas.
for or while? Use for when you know how many times the loop will run: from 1 to 10, or once for every element of a vector (that's the next exercise). Use while when you don't know 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++;
}
std::cout << "Doublings: " << doublings << std::endl;
std::cout << "Number: " << number << std::endl;Doublings: 10
Number: 1024Instructions
- 1
Rewrite the
whileloop in the editor as aforloop, and delete thewhileloop. The program still prints the numbers from 1 to 5. - 2
Change your loop so that it prints the numbers from 1 to 10, including 10.
- 3
Below it, write a second
forloop that counts down from 20 to 0 by fives:20,15,10,5and0, each on its own line. Usei -= 5as the step.