How to break out of nested loops in C++

In this tutorial, we will learn to break out of nested loops in C++.  In different languages, we use break statement to exit from a for loop. But, this break statement always works in a single loop not in a nested loop.

To break from a nested loop, we can take the help of flags. Basically, Flag variable is used as a signal in programming. This signal will let the program know that a specific condition has been met. When a certain condition has been met then we will use the break statement to break from a loop. Initially, we set the flag value to 0, and if a certain condition has reached, we will then set flag value to 1.

For better understanding, follow the below example:

Suppose we want to find the number “20” in a 2D matrix. If found, print “element found” otherwise, print “not found”.

In the below example, we are breaking the nested loop with the help of both flag variable and break statement.

An example C++ program to show how to beak out or exit from a nested loop in C++

 

#include<iostream>
using namespace std;

int main() {
    int array[3][3] = {
                        {1, 2, 3}, 
                        {10, 20, 30}, 
                        {34, 45, 34}
                    };
    int find = 20;
    
    int flag = 0; // make a flag variable to check that we have to break or not
    for(int i = 0; i < 3; i++) {
        for(int j = 0; j < 3; j++) {
            if(array[i][j] == find) {
                flag = 1; // setting flag to 1 and use break
                break;
            }
        }
        if(flag == 1) { // flag will be 1 only when we have encountered a break in nested loop
            cout << "element found" << endl;
            break;
        }
    }
    if(flag == 0) {  
        cout << "element not found" << endl;
    }
    
}

OUTPUT:

element found

Also Check: how to convert string to hexadecimal in c++

Leave a Reply

Your email address will not be published. Required fields are marked *