Loops
To do the same thing many times, you don't copy the code many times: you write a loop. Loops are where Step is at its best: press it and watch the program go round and round, the variables changing each time.
1#include <iostream>2 3int main() {4 int n = 3;5 while (n > 0) {6 std::cout << n << '\n';7 n--;8 }9 std::cout << "Go!\n";10 return 0;11}
3 2 1 Go!
The while loop
while first checks the condition in the parentheses. If it is true, the loop body runs once, then it goes back to the top and checks again. If it is false, the body is skipped and the program carries on below.
A loop that stops usually has three things:
- Before it starts, a variable gets a starting value (
int n = 3;above). - Each time round, the condition is checked first (
n > 0). - The body changes the variable (
n--), so that one day the condition becomes false.
while fits best when you don't know how many times it will go round. Say you save 800 a month: how many months until you have 5000?
1#include <iostream>2 3int main() {4 int saved = 0;5 int months = 0;6 while (saved < 5000) {7 saved += 800;8 months++;9 }10 std::cout << months << " months, saved " << saved << '\n';11 return 0;12}
7 months, saved 5600
The for loop
Counting "from 1 to 5" is so common that C++ has a way to put all three things on one line:
1#include <iostream>2 3int main() {4 for (int i = 1; i <= 5; i++) {5 std::cout << "Time " << i << '\n';6 }7 return 0;8}
Time 1 Time 2 Time 3 Time 4 Time 5
for (start; condition; change): first int i = 1 runs once. Then each time round it checks i <= 5; if true, the body runs, then i++, then back to the condition.
An i declared in the parentheses only exists inside this loop, and is gone when the loop ends. Several loops can each have their own i.
What number does this show?
1#include <iostream>2 3int main() {4 int count = 0;5 for (int i = 0; i < 10; i += 3) {6 count++;7 }8 std::cout << count << '\n';9 return 0;10}
i is 0, 3, 6 and 9 in turn; all four are less than 10, so the body runs 4 times. Next i becomes 12, the condition is false, and the loop ends.
Totals and counts
The two jobs loops do most: adding up a series of numbers, and counting how many meet a condition. Both work the same way: get a variable ready at 0, and add to it each time round.
1#include <iostream>2 3int main() {4 int total = 0;5 int even = 0;6 for (int i = 1; i <= 10; i++) {7 total += i;8 if (i % 2 == 0) {9 even++;10 }11 }12 std::cout << "Sum of 1 to 10: " << total << '\n';13 std::cout << "Even numbers: " << even << '\n';14 return 0;15}
Sum of 1 to 10: 55 Even numbers: 5
Press Step and keep an eye on total: 0, 1, 3, 6, 10… each time round it adds one more i.
Note: Declare total outside the loop. Inside the body, it would start again at 0 every time round and end up adding nothing.
do while
do while runs the body first and checks the condition after. So its body runs at least once:
1#include <iostream>2 3int main() {4 int n = 10;5 while (n < 5) {6 std::cout << "while: " << n << '\n';7 n++;8 }9 do {10 std::cout << "do while: " << n << '\n';11 n++;12 } while (n < 5);13 return 0;14}
do while: 10
Both loops have the same condition, and n < 5 is false for both. The while body never runs; the do while body runs once, and only then finds out it should stop. Note the semicolon after the while (...) at the end of do while.
break and continue
break leaves the whole loop at once; continue skips the rest of this time round and goes straight on to the next.
1#include <iostream>2 3int main() {4 for (int i = 1; i <= 10; i++) {5 if (i % 3 == 0) {6 continue;7 }8 if (i > 7) {9 break;10 }11 std::cout << i << " ";12 }13 std::cout << '\n';14 return 0;15}
1 2 4 5 7
3 and 6 are skipped by continue; at 8, break ends the loop, so 9 and 10 never get a turn.
break is great for searching: once you've found it, stop looking. Here is the first two-digit number divisible by 7:
1#include <iostream>2 3int main() {4 int found = 0;5 for (int n = 10; n < 100; n++) {6 if (n % 7 == 0) {7 found = n;8 break;9 }10 }11 std::cout << found << '\n';12 return 0;13}
14
Nested loops
A loop body can hold another loop. Each time the outer loop goes round once, the inner loop runs all the way through. That's how you make a times table:
1#include <iostream>2 3int main() {4 for (int row = 1; row <= 4; row++) {5 for (int col = 1; col <= row; col++) {6 std::cout << col << "x" << row << "=" << col * row << "\t";7 }8 std::cout << '\n';9 }10 return 0;11}
1x1=1 1x2=2 2x2=4 1x3=3 2x3=6 3x3=9 1x4=4 2x4=8 3x4=12 4x4=16
The outer row says which line it is; the inner col goes from 1 to row, so line 1 has one entry and line 4 has four. At the end of each line, '\n' starts a new one (it is outside the inner loop). Press Step to see how row and col change together.
Infinite loops
If the condition is always true, the loop never stops: an infinite loop. The most common cause is forgetting to change the variable:
1int n = 3;2while (n > 0) {3 std::cout << n << '\n';4}
There is no n-- in the body, so n stays 3, n > 0 stays true, and the program shows 3 forever. In a terminal, the only way out is Ctrl+C. On this page, a program that runs too many steps without finishing is stopped, and you are told so.
When a program won't stop, check three things: is the condition right? Does the body change the variable? Does it change in the right direction (subtracting where you meant to add never gets there)?
Sometimes while (true) is written on purpose, with a break inside to get out. That's fine, as long as you're sure the break is reached.
Practice
Write the code, then press Check. A hint costs nothing; the answer is there when you need it.
Multiply 1 to 6
✓Use a loop to work out 1 × 2 × 3 × 4 × 5 × 6 and show the result, 720.
720
1#include <iostream>2 3int main() {4 int product = 1;5 6 std::cout << product << '\n';7 return 0;8}
Doubling the savings
✓balance starts at 1000 and grows by 10% a year (balance = balance * 1.1;). In the first blank line, use while to find how many years until it is 2000 or more; in the second, do it again with 20% a year (* 1.2).
10%: 8 years 20%: 4 years
1#include <iostream>2 3int main() {4 double balance = 1000;5 int years = 0;6 7 std::cout << "10%: " << years << " years\n";8 balance = 1000;9 years = 0;10 11 std::cout << "20%: " << years << " years\n";12 return 0;13}
A triangle of stars
✓Use nested loops to show this triangle: one * on line 1, two on line 2, up to line 4.
* ** *** ****
1#include <iostream>2 3int main() {4 5 return 0;6}
What you learned
while (condition)checks first, then runs, and keeps going while the condition is true; good when you don't know how many times.for (start; condition; change)puts all three on one line, good for counting; a variable declared in the parentheses exists only inside the loop.- Totals and counts: a variable outside the loop, starting at 0, added to each time round.
do whileruns first and checks after, so the body runs at least once; it ends with a semicolon.breakleaves the whole loop,continuejumps to the next time round; with nested loops, the inner loop runs all the way through for each time round of the outer one.- A condition that is always true makes an infinite loop; check the condition and whether the variable changes in the right direction.