Using break in Nested Loops
How can I break out of nested loops using the break keyword?
When using nested loops, the break
keyword only breaks out of the innermost loop in which it is used. If you want to break out of multiple levels of nested loops, you can use a flag variable:
#include <iostream>
int main() {
bool breakOut{false};
for (int i{0}; i < 5; ++i) {
for (int j{0}; j < 5; ++j) {
if (i == 2 && j == 3) {
breakOut = true;
break;
}
std::cout << "(" << i << ", " << j << ")\n";
}
if (breakOut) break;
}
}
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 0)
(1, 1)
(1, 2)
(1, 3)
(1, 4)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
Conditionals and Loops
Learn the fundamentals of controlling program flow in C++ using if statements, for loops, while loops, continue, and break