The break Statement
Sometimes you don't need to go through the whole loop. When you are looking for something and you find it, there is no reason to keep looking. The break statement ends the loop immediately, and the program continues with the code after the loop.
Let's find the first number from 100 up that is divisible by 7. The loop prints each number it checks, so that you can see where it stops:
for (int number = 100; number < 200; number++) {
std::cout << "Checking " << number << std::endl;
if (number % 7 == 0) {
std::cout << "First multiple of 7: " << number << std::endl;
break;
}
}
std::cout << "Done" << std::endl;Checking 100
Checking 101
Checking 102
Checking 103
Checking 104
Checking 105
First multiple of 7: 105
DoneThe condition number % 7 == 0 is true when the remainder after dividing by 7 is 0. When the loop gets to 105, the condition is true. The program prints the result, and break ends the loop: the numbers from 106 on are never checked, and the program goes on with the line that prints Done. Without break, the loop would run all the way to 199 and print all 14 multiples of 7, not just the first one.
You will almost always put break inside an if. On its own, it would end the loop during its very first iteration. break works the same way in while and for loops.
Often you also need to know after the loop what you found, or whether you found anything at all. Then store the result in a variable created before the loop, with a value that means “not found”, such as -1 for an index:
std::vector<std::string> names = {"Adam", "Eva", "Peter", "Eva"};
int position = -1;
for (int i = 0; i < names.size(); i++) {
if (names[i] == "Eva") {
position = i;
break;
}
}
if (position == -1) {
std::cout << "Not found" << std::endl;
} else {
std::cout << "Eva is at index " << position << std::endl;
}Eva is at index 1Thanks to break, you get the first Eva, at index 1. Without it, the loop would go on, and position would end up as 3, the index of the last Eva.
Instructions
- 1
The vector
temperaturesholds morning temperatures in the order they were measured, and the loop prints each one as it checks it. In the loop, below the line that printsChecking, add anifthat printsFirst frost:and the temperature for every temperature below zero. Run the program: it printsFirst frost:three times, but only the first one is right. - 2
Add
breakto the block of theif, after the printing, so that the loop stops at the first frost. Now the output ends withChecking -3andFirst frost: -3, and the remaining temperatures are never checked.