Computers are good at doing the same thing many times without getting bored or making slips. So far, printing ten lines took ten statements. A loop is a statement that runs a block of code again and again, so that you write the block once.
while repeats a block as long as a condition is true
A while loop looks like an if statement: a condition in round brackets, then a block in braces. The difference is what happens after the block. The computer checks the condition; if it is true, it runs the block, then goes back and checks again. The loop ends when the condition is false.
#include <iostream>
int main() {
int countdown = 3;
while (countdown > 0) {
std::cout << countdown << '\n';
countdown = countdown - 1;
}
std::cout << "Lift off!\n";
}This prints 3, 2, 1 and then Lift off!. Each run of the block is called an iteration. This loop has three iterations.
Counting has three parts
Very often you want a block to run a fixed number of times. That takes a variable that counts the iterations, called a counter, and three pieces of code:
#include <iostream>
int main() {
int i = 1; // 1. where the counter starts
while (i <= 3) { // 2. the condition for carrying on
std::cout << "Lap " << i << '\n';
i = i + 1; // 3. the step: move the counter on
}
}This prints Lap 1, Lap 2 and Lap 3. The name i is the traditional name for a loop counter.
Adding to a variable is so common that C++ has shorter ways to write it:
total += 5;meanstotal = total + 5;. There are also-=,*=and/=.++i;meansi = i + 1;, and--i;meansi = i - 1;.
for puts the three parts on one line
In the loop above, the three parts are spread over five lines, and it is easy to forget the step. A for loop writes all three inside one pair of round brackets, separated by semicolons: the start, the condition, the step.
#include <iostream>
int main() {
for (int i = 1; i <= 3; ++i) {
std::cout << "Lap " << i << '\n';
}
}This prints the same three lines. The computer does exactly what the while version did: it runs the start once, then repeats "check the condition, run the block, do the step" until the condition is false.
Use for when you can say in advance how many iterations you want. You will meet two standard shapes:
for (int i = 1; i <= n; ++i)runsntimes, anditakes the values 1, 2, up ton.for (int i = 0; i < n; ++i)also runsntimes, anditakes the values 0, 1, up ton - 1.
Programmers use the second shape most, because counting from zero turns out to be convenient later on. When the numbers are shown to a person, as in Lap 1, the first shape is usually what you want.
A running total
A loop often builds up an answer in a variable that is defined before the loop and changed in every iteration. Such a variable is called a running total. This program adds the numbers 1 to 4:
#include <iostream>
int main() {
int total = 0;
for (int i = 1; i <= 4; ++i) {
total += i;
}
std::cout << total << '\n';
}This prints 10. Step through the diagram to watch the two variables change.
total starts at 0 before the loop. In each iteration the current value of i is added to it. When i reaches 5 the condition i <= 4 is false and the loop ends.The line int total = 0; must be before the loop. Inside the block it would run in every iteration and start the total again each time.
while for when you cannot count in advance
Use while when you cannot say beforehand how many iterations there will be. This program keeps asking until the user types the right word. (It reads input, so run it in the C++ playground with a few lines of standard input, such as open, please and sesame.)
#include <iostream>
#include <string>
int main() {
std::string word;
std::cout << "Password: ";
std::getline(std::cin, word);
while (word != "sesame") {
std::cout << "Wrong. Try again.\n";
std::cout << "Password: ";
std::getline(std::cin, word);
}
std::cout << "Welcome.\n";
}Notice that the block changes word. If nothing in the block could change the condition, the loop would run for ever. That is called an infinite loop. This one never stops, because n stays at 1:
#include <iostream>
int main() {
int n = 1;
while (n < 5) {
std::cout << n << '\n';
}
}On this site an infinite loop is cut off after a time limit. On your own computer, press Ctrl+C to stop a program that will not finish.
Off-by-one mistakes
The most common loop mistake is running one iteration too many or one too few. It is so common that it has a name: an off-by-one mistake. This program is meant to print the 3 times table up to 3 × 5:
#include <iostream>
int main() {
for (int i = 1; i < 5; ++i) {
std::cout << "3 x " << i << " = " << 3 * i << '\n';
}
}It prints only four lines and stops at 3 x 4 = 12. The condition i < 5 is false when i is 5, so the fifth line never appears. The fix is i <= 5.
To check a loop, work out its first and last iteration by hand. Ask: what value does the counter have the first time the block runs? What value does it have the last time? How many iterations is that?
Two errors you will meet
Using the counter after the loop. A variable defined in the round brackets of a for exists only inside that loop.
#include <iostream>
int main() {
for (int i = 0; i < 3; ++i) {
std::cout << i << '\n';
}
std::cout << i << '\n';
}main.cpp: In function 'int main()':
main.cpp:7:18: error: 'i' was not declared in this scope
7 | std::cout << i << '\n';
| ^You have met "was not declared in this scope" for a misspelt name. Here the name is spelt correctly, but line 7 is outside the loop, where i no longer exists. The part of a program in which a variable exists is called its scope. The same rule holds for a variable defined inside any block: it exists until that block's closing brace. A value that is needed after the loop, such as a running total, must be defined before the loop.
Commas where semicolons belong. The three parts of a for are separated by semicolons.
#include <iostream>
int main() {
for (int i = 0, i < 3, ++i) {
std::cout << i << '\n';
}
}main.cpp: In function 'int main()':
main.cpp:4:22: error: expected ';' before '<' token
4 | for (int i = 0, i < 3, ++i) {
| ^~
| ;
main.cpp:4:23: error: expected primary-expression before '<' token
4 | for (int i = 0, i < 3, ++i) {
| ^
main.cpp:4:31: error: expected ';' before ')' token
4 | for (int i = 0, i < 3, ++i) {
| ^
| ;Three errors, all on line 4 and all with one cause. The first and the last both say expected ';', which is the clue: the compiler is looking for the two semicolons of a for and cannot find them. Replace both commas with semicolons and all three messages disappear.
What you can do now
You can repeat a block with while, count iterations with for, build up a running total, and check a loop's first and last iteration for off-by-one mistakes. In the exercises you will predict what loops print, then write a program that reads several numbers and adds them up.
Next: name a step with a function, and finish a complete program.