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 .
// 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;
}