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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Conditional Operator Precedence
What is the precedence of the conditional (ternary) operator compared to other operators?
Condition in a do-while Loop
Is it possible to have a condition that always evaluates to false in a do-while loop?
Short-Circuit Evaluation Order
In what order are the conditions evaluated in short-circuit evaluation?
Detecting Infinite Loops
How can I detect and prevent infinite loops in my C++ code?
Scope of Loop Variables
What is the scope of variables declared within the initialization statement of a for loop?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant