Conditionals and Loops

Using break in Nested Loops

How can I break out of nested loops using the break keyword?

Abstract art representing computer programming

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)
This Question is from the Lesson:

Conditionals and Loops

Learn the fundamentals of controlling program flow in C++ using if statements, for loops, while loops, continue, and break

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Conditionals and Loops

Learn the fundamentals of controlling program flow in C++ using if statements, for loops, while loops, continue, and break

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved