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:
C++
// C++ program to illustrate // Linear Search #include <iostream> using namespace std; void findElement( int arr[], int size, int key) { // loop to traverse array and search for key for ( int i = 0; i < size; i++) { if (arr[i] == key) { cout << "Element found at position: " << (i + 1); } } } // Driver program to test above function int main() { int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = 6; // no of elements int key = 3; // key to be searched // Calling function to find the key findElement(arr, n, key); return 0; } |
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:
Example:
C++
// C++ program to illustrate // using break statement // in Linear Search #include <iostream> using namespace std; void findElement( int arr[], int size, int key) { // loop to traverse array and search for key for ( int i = 0; i < size; i++) { if (arr[i] == key) { cout << "Element found at position: " << (i + 1); // using break to terminate loop execution break ; } } } // Driver program to test above function int main() { int arr[] = { 1, 2, 3, 4, 5, 6 }; // no of elements int n = 6; // key to be searched int key = 3; // Calling function to find the key findElement(arr, n, key); return 0; } |
Element found at position: 3
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.
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.