![]() |
VOOZH | about |
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.
Example: Using break with simple loops
1 2 3 4 5
Explanation:
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.
*** *** *** *** ***
Explanation:
The break statement can be included in an infinite loop with a condition in order to terminate the execution of the infinite loop.
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:
1 2 3 4 5 6 7 8 9 10
Explanation: The above code restricts the number of loop iterations to 10. Apart from this, the break can be used in Switch case statements too.