/* */ Click to Join Live Class with Shankar sir Call 9798158723

Break Statement in C++


It is one of the most important statements is the break statement in C++ and let’s see how to use the C++ break label.break is used to break or terminate a loop whenever we want.Just type break; after the statement after which you want to break the loop.

When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement .


Syntex :-

for(.....)
{
......
if(error1)
break;
.....
} break;

Q.) Example og Break Statement in 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;
}
Output
Element found at position: 3