Break with Infinite Loops

The break statement can be included in an infinite loop with a condition in order to terminate the execution of the infinite loop.
Example:

C++




// C++ program to illustrate
// using break statement
// in Infinite loops
#include <iostream>
using namespace std;
  
int main()
{
    // loop initialization expression
    int i = 0;
  
    // infinite while loop
    while (1) {
        cout << i << " ";
        i++;
    }
  
    return 0;
}


Output:

Execution timed out 

Note: Please do not run the above program in your compiler as it is an infinite loop so you may have to forcefully exit the compiler to terminate the program.

In the above program, the loop condition based on which the loop terminates is always true. So, the loop executes an infinite number of times. We can correct this by using the break statement as shown below:

C++




// C++ program to illustrate
// using break statement
// in Infinite loops
#include <iostream>
using namespace std;
  
int main()
{
    // loop initialization expression
    int i = 1;
  
    // infinite while loop
    while (1) {
        if (i > 10)
            break;
  
        cout << i << " ";
        i++;
    }
  
    return 0;
}


Output

1 2 3 4 5 6 7 8 9 10 

The above code restricts the number of loop iterations to 10. Apart from this, the break can be used in Switch case statements too.



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

...