The C++ Break Statement can be considered to be a loop control statement that can be used to terminate the loop. At the moment when a break statement is found from within a loop, the loop iterations stop over there and the control usually returns from the loop just there to the first statement after the loop.
Generally, break statements can be used in situations where we generally are not sure about the true count of iterations for the loop or we would wish to terminate the loop that will be based on some condition.
We are going to see here the application of break statements that will be seeing in three different types of loops:
Let us now go to look at the examples that will be for each of the above three types of loops using a break statement.
Break with Simple loops
Considering the situation in which we want to search for some element in an array. For doing this, we will use a loop for traversing the array that will be starting from the first index and we will compare the array elements with the particular key.
Element is found at the position: 3
The above code will run absolutely fine i.e. with no errors. But the above code can not be considered to be efficient. The above code generally completes all the iterations even after the element will be found. Considering the situation where there are 1000 elements in the array and the key that is to be searched will be present at 1st position so, in that case, the above approach is going to execute a total of 999 iterations which generally are of no purpose and are completely useless.
To avoid such useless iterations, we are allowed to use the break statement in our program
Break with Nested Loops
We are also allowed to use break statements during the work with nested loops. If the break statement will be used in the innermost loop. The control is supposed to come out only from the innermost loop.
Break with Infinite Loops
The break statement can also be included in any infinite loop but it should be with a condition in order for terminating the execution of the infinite loop.