The while Loop
Imagine you need to print the numbers from 1 to 100. You could write std::cout a hundred times, but it would take ages, and changing anything later would be even worse. Programs repeat work like this all the time: they go through every student in a class, check every product in a shop, or redraw a game screen 60 times a second. That is what loops are for. A loop is a piece of code that runs again and again.
The simplest loop is while. It repeats a block of code while its condition is true:
int number = 1;
while (number <= 5) {
std::cout << number << std::endl;
number++;
}This prints:
1
2
3
4
5A while loop looks like an if: the keyword, a condition in parentheses and a block of code in curly braces. The difference is that if runs its block at most once, but while keeps coming back to the condition. Step by step:
- The program creates
numberwith the value1. - It checks the condition
number <= 5. It is true, so the program runs the block: it prints1, andnumber++increasesnumberto2. - It goes back to the condition.
2 <= 5is still true, so it prints2and increasesnumberto3. - And so on, until
numberis6. Then the condition is false, the loop ends, and the program continues with the code after the loop's closing brace}.
Each run of the block is called an iteration. This loop has five iterations. To print the numbers up to 100, you would only change 5 to 100.
The code after the loop runs only once, when the loop has finished:
int number = 1;
while (number <= 3) {
std::cout << number << std::endl;
number++;
}
std::cout << "Done" << std::endl;1
2
3
DoneNotice the line number++. Something in the block must change the variable in the condition, so that the condition becomes false at some point. Without it, the loop would never end. You'll see what happens then in the next exercise.
Instructions
- 1
Delete the three lines that print 1, 2 and 3. In their place, create a variable
numberof typeintwith the value10. The loop will count with it. - 2
Below it, write a
whileloop that runs whilenumberis less than or equal to20. Inside the loop, printnumberon its own line and then increase it by 1. The program prints the numbers from 10 to 20, each on its own line. - 3
After the loop, below its closing brace
}, printAfter the loop:and the value ofnumber. The last line of the output isAfter the loop: 21. The variable ends up as 21, not 20, because the loop stops only when the condition is false.