Break and Continue
A loop checks its condition once per round. Sometimes you find out in the middle of the body that you want to stop. Two statements help here:
breakends the whole loop right away.continueends only the current round. The loop goes on with the next round.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 1) {
continue;
}
if (i == 8) {
break;
}
cout << i << " ";
}
cout << "\n";
return 0;
}
Output:
2 4 6
Follow the rounds one by one:
i | What happens |
|---|---|
| 1 | odd, so continue: nothing printed |
| 2 | even and not 8: printed |
| 3, 5, 7 | odd, skipped |
| 4, 6 | printed |
| 8 | break: the loop ends |
The loop was set up for 10 rounds, but 9 and 10 never ran. In a for loop, continue still runs the step (i++) before the next round, so the counter keeps moving.
You saw break in the Switch Statement lesson. It does the same job here: it leaves the loop at once.
Loop until a stop signal
break is often used with while (true). On its own, while (true) never ends, because its condition is always true. A break inside it gives the loop a way out. This is useful when you only know that it is time to stop after you read a value:
int number;
while (true) {
cin >> number;
if (number == 0) {
break;
}
cout << "Got " << number << "\n";
}
cout << "Stopped" << "\n";
Output:
Got 7
Got 3
Stopped
The input was 7, 3, 0 and 5. When the program read the 0, break ended the loop. The 5 was never read.
Use break and continue only where they make the loop easier to follow. A loop with many of them is hard to read, because you have to find every exit to know what it does.
In the exercise, read numbers, skip the negative ones with continue, stop at 0 with break, and add up the rest.