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.
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.
We will see here the usage of break statements with three different types of loops:
- Simple loops
- Nested loops
- Infinite loops
Let us now look at the examples for each of the above three types of loops using a break statement.
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.
Element found at position: 3
The above code runs fine with no errors. But the above code is not efficient. The above code completes all the iterations even after the element is found. Suppose there are 1000 elements in the array and the key to be searched is present at 1st position so the above approach will execute 999 iterations which are of no purpose and are useless.
To avoid these useless iterations, we can use the break statement in our program. Once the break statement is encountered the control from the loop will return immediately after the condition gets satisfied. So will use the break statement with the if condition which compares the key with array elements as shown below:
Element found at position: 3
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.
*** *** *** *** ***
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.
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.
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
The above code restricts the number of loop iterations to 10. Apart from this, the break can be used in Switch case statements too.
Please Login to comment...