Break Statement in C/C++

The break in C or C++ is a loop control statement which is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stops there and control returns from the loop immediately to the first statement after the loop.
Syntax:

break;

Basically break statements are used in the 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 statement with three different types of loops:

  1. Simple loops
  2. Nested loops
  3. Infinite loops

Let us now look at the examples for each of the above three types of loops using break statement.



  1. Simple loops: Consider the situation where we want to search 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.
    Below is the implementation of this idea:

C

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to illustrate 
// Linear Search 
  
#include <stdio.h>
  
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) { 
            printf("Element found at position: %d", (i + 1)); 
        
    
  
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;
}

chevron_right


C++

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right