Loop Flow: break, continue, Nested Loops
All loop examples you’ve seen, so far, run to completion. But that’s not always what we want. For example, you’re searching for a name in a list of ninety people, and you find a match on the third one you check. Do you really want to keep checking the other eighty-seven?
You need a way to jump out of a loop early, but also a way to skip just one iteration without ending the loop. The break and continue keywords let you do that.
Breaking out of a loop early
break immediately ends the loop it’s in, with the execution jumping straight to the first line after the loop.
Here’s an example that checks whether 91 is a prime number.
91 is not a prime as it equals 7 times 13. The loop checks divisors starting at 2, and stops the moment it finds one that divides evenly. That happens at divisor 7, so the loop doesn’t waste more iterations.
Skipping an iteration with continue
continue skips the rest of the current iteration’s body and moves straight to the next one. But note:
- In a
whileloop, that means jumping back to re-check the stopping condition. - In a
forloop, it means jumping to the increment step first, before the stopping condition.
Here’s a program that adds up donation amounts entered one at a time, and stops when the user enters 0:
In the while expression, std::cin >> amount evaluates to true each time a number is read successfully, and amount != 0 ensures that the user intends to keep going.
When a negative number comes in, continue skips adding it to the total and jumps straight back to the while expression.
Nested loops
A nested loop is simply a loop written inside the body of another loop. The outer loop runs once, and for each of its iterations, the entire inner loop runs from start to finish.
Here’s an example that prints a multiplication table:
For row = 1, the inner loop runs five times, then a newline is printed, then row becomes 2 and the inner loop runs completely again. And so on.
Break and continue inside nested loops
When break appears inside the innermost loop, it only exits that and doesn’t interfere with the workings of the outer loop.
For example, you want to find the first pair of numbers between 1 and 10 whose product is 20. A first attempt might look like this:
The break is executed as soon as row * col hits 20, but it only ends the inner col loop (for that particular row). The outer row loop keeps going, so the search continues and ends up printing multiple pairs.
If all you wanted was the first matching pair, one break isn’t enough. Think about how you’d fix this.
Here’s one way:
This is what changed:
- We introduced a new variable,
found, and used it in the stopping condition of the outer loop. - Right after
foundis set totruein an iteration of the inner loop, the outer loop will also stop its execution on the next pass, so the search ends the moment the first pair is printed.
continue behaves the same way in nested loops: it only affects the loop it’s written inside. A continue inside the col loop skips to the next col, not the next row.
Checkpoint
Given this code, what gets printed?
int attempt = 0;
int secret = 7;
for (int guess = 1; guess <= 10; guess++) {
attempt++;
if (guess == secret) {
break;
}
}
std::cout << "Number of attempts: " << attempt;Given this code, what gets printed?
for (int i = 1; i <= 5; i++) {
std::cout << i << " ";
if (i == 3) {
continue;
}
}Given this code, how many times does it print “Outer” and how many times does it print “Inner”?
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
if (col == 2) {
continue;
}
std::cout << "Inner" << std::endl;
}
std::cout << "Outer" << std::endl;
}