Break with Nested Loops

We can also use break statements while working with nested loops. If the break statement is used in the innermost loop. The control will come out only from the innermost loop. 

Example:

C++




// C++ program to illustrate
// using break statement
// in Nested loops
#include <iostream>
using namespace std;
  
int main()
{
  
    // nested for loops with break statement
    // at inner loop
    for (int i = 0; i < 5; i++) {
        for (int j = 1; j <= 10; j++) {
            if (j > 3)
                break;
            else
                cout << "*";
        }
        cout << endl;
    }
  
    return 0;
}


Output

***
***
***
***
***

In the above code, we can clearly see that the inner loop is programmed to execute for 10 iterations. But as soon as the value of j becomes greater than 3 the inner loop stops executing which restricts the number of iterations of the inner loop to 3 iterations only. However, the iteration of the outer loop remains unaffected.
Therefore, break applies to only the loop within which it is present.

C++ Break Statement

The break in C++ is a loop control statement that is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stop there and control returns from the loop immediately to the first statement after the loop.

Syntax:

break;

Basically, break statements are used in situations when we are not sure about the actual number of iterations for the loop or we want to terminate the loop based on some condition.

Image showing the working of  break

We will see here the usage of break statements with three different types of loops:

  1. Simple loops
  2. Nested loops
  3. Infinite loops

Let us now look at the examples for each of the above three types of loops using a break statement.

Similar Reads

Break with Simple loops

Consider the situation where we want to search for an element in an array. To do this, use a loop to traverse the array starting from the first index and compare the array elements with the given key.Example:...

Break with Nested Loops

...

Break with Infinite Loops

...