Break Statement in C/C++ - GeeksforGeeks

20 Nov, 2019
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:
Simple loopsNested loopsInfinite loops
Simple loops
Nested loops
Infinite loops
Let us now look at the examples for each of the above three types of loops using break statement.
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:CC++C// 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;}C++// 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 functionint 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;}Output:Element found at index: 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:CC++C// C program to illustrate// using break statement // in 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));                // using break to terminate loop execution            break;        }    }}  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;}C++// CPP 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 functionint 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;}Output:Element found at position: 3
Nested Loops: We can also use break statement 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. Below is the example of using break with nested loops:CC++C// C program to illustrate// using break statement // in Nested loops#include <stdio.h>  int main() {    // nested for loops with break statement    // at inner loop    for (int i = 0; i < 5; i++) {        for (int j = 1; j <= 10; j++) {            if (j > 3)                break;            else                printf("*");        }        printf("\n");    }       return 0;}C++// CPP program to illustrate// using break statement // in Nested loops#include <iostream>using namespace std;  int main(){      // nested for loops with break statement    // at inner loop    for (int i = 0; i < 5; i++) {        for (int j = 1; j <= 10; j++) {            if (j > 3)                break;            else                cout << "*";        }        cout << endl;    }      return 0;}Output:***
***
***
***
***
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 iteration of the inner loop to 3 iterations only. However the iteration of outer loop remains unaffected.Therefore, break applies to only the loop within which it is present.Infinite Loops: break statement can be included in an infinite loop with a condition in order to terminate the execution of the infinite loop.Consider the below infinite loop:CC++C// C program to illustrate// using break statement // in Infinite loops#include <stdio.h>  int main() {    // loop initialization expression    int i = 0;       // infinite while loop    while (1) {        printf("%d ", i);        i++;    }       return 0;}C++// CPP program to illustrate// using break statement // in Infinite loops#include <iostream>using namespace std;  int main(){    // loop initialization expression    int i = 0;      // infinite while loop    while (1) {        cout << i << " ";        i++;    }      return 0;}Note: Please donot 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 infinite number of times. We can correct this by using the break statement as shown below:CC++C// C program to illustrate// using break statement // in Infinite loops#include <stdio.h>  int main() {    // loop initialization expression    int i = 1;       // infinite while loop    while (1) {        if (i > 10)            break;           printf("%d ", i);        i++;    }       return 0;}C++// CPP program to illustrate// using break statement // in Infinite loops#include <iostream>using namespace std;  int main(){    // loop initialization expression    int i = 1;      // infinite while loop    while (1) {        if (i > 10)            break;          cout << i << " ";        i++;    }      return 0;}Output:1 2 3 4 5 6 7 8 9 10 
The above code restricts the number of loop iterations to 10.
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:CC++C// 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;}C++// 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 functionint 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;}Output:Element found at index: 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:CC++C// C program to illustrate// using break statement // in 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));                // using break to terminate loop execution            break;        }    }}  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;}C++// CPP 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 functionint 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;}Output:Element found at position: 3

C
C++
// 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;}
// 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 functionint 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 index: 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:
C
C++
// C program to illustrate// using break statement // in 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));                // using break to terminate loop execution            break;        }    }}  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;}
// CPP 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 functionint 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;}
Output:
Element found at position: 3

Nested Loops: We can also use break statement 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. Below is the example of using break with nested loops:CC++C// C program to illustrate// using break statement // in Nested loops#include <stdio.h>  int main() {    // nested for loops with break statement    // at inner loop    for (int i = 0; i < 5; i++) {        for (int j = 1; j <= 10; j++) {            if (j > 3)                break;            else                printf("*");        }        printf("\n");    }       return 0;}C++// CPP program to illustrate// using break statement // in Nested loops#include <iostream>using namespace std;  int main(){      // nested for loops with break statement    // at inner loop    for (int i = 0; i < 5; i++) {        for (int j = 1; j <= 10; j++) {            if (j > 3)                break;            else                cout << "*";        }        cout << endl;    }      return 0;}Output:***
***
***
***
***
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 iteration of the inner loop to 3 iterations only. However the iteration of outer loop remains unaffected.Therefore, break applies to only the loop within which it is present.
C
C++
// C program to illustrate// using break statement // in Nested loops#include <stdio.h>  int main() {    // nested for loops with break statement    // at inner loop    for (int i = 0; i < 5; i++) {        for (int j = 1; j <= 10; j++) {            if (j > 3)                break;            else                printf("*");        }        printf("\n");    }       return 0;}
// CPP program to illustrate// using break statement // in Nested loops#include <iostream>using namespace std;  int main(){      // nested for loops with break statement    // at inner loop    for (int i = 0; i < 5; i++) {        for (int j = 1; j <= 10; j++) {            if (j > 3)                break;            else                cout << "*";        }        cout << endl;    }      return 0;}
Output:
***
***
***
***
***

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 iteration of the inner loop to 3 iterations only. However the iteration of outer loop remains unaffected.Therefore, break applies to only the loop within which it is present.
Infinite Loops: break statement can be included in an infinite loop with a condition in order to terminate the execution of the infinite loop.Consider the below infinite loop:CC++C// C program to illustrate// using break statement // in Infinite loops#include <stdio.h>  int main() {    // loop initialization expression    int i = 0;       // infinite while loop    while (1) {        printf("%d ", i);        i++;    }       return 0;}C++// CPP program to illustrate// using break statement // in Infinite loops#include <iostream>using namespace std;  int main(){    // loop initialization expression    int i = 0;      // infinite while loop    while (1) {        cout << i << " ";        i++;    }      return 0;}Note: Please donot 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 infinite number of times. We can correct this by using the break statement as shown below:CC++C// C program to illustrate// using break statement // in Infinite loops#include <stdio.h>  int main() {    // loop initialization expression    int i = 1;       // infinite while loop    while (1) {        if (i > 10)            break;           printf("%d ", i);        i++;    }       return 0;}C++// CPP program to illustrate// using break statement // in Infinite loops#include <iostream>using namespace std;  int main(){    // loop initialization expression    int i = 1;      // infinite while loop    while (1) {        if (i > 10)            break;          cout << i << " ";        i++;    }      return 0;}Output:1 2 3 4 5 6 7 8 9 10 
The above code restricts the number of loop iterations to 10.
C
C++
// C program to illustrate// using break statement // in Infinite loops#include <stdio.h>  int main() {    // loop initialization expression    int i = 0;       // infinite while loop    while (1) {        printf("%d ", i);        i++;    }       return 0;}
// CPP program to illustrate// using break statement // in Infinite loops#include <iostream>using namespace std;  int main(){    // loop initialization expression    int i = 0;      // infinite while loop    while (1) {        cout << i << " ";        i++;    }      return 0;}
Note: Please donot 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 infinite number of times. We can correct this by using the break statement as shown below:
C
C++
// C program to illustrate// using break statement // in Infinite loops#include <stdio.h>  int main() {    // loop initialization expression    int i = 1;       // infinite while loop    while (1) {        if (i > 10)            break;           printf("%d ", i);        i++;    }       return 0;}
// CPP program to illustrate// using break statement // in Infinite loops#include <iostream>using namespace std;  int main(){    // loop initialization expression    int i = 1;      // infinite while loop    while (1) {        if (i > 10)            break;          cout << i << " ";        i++;    }      return 0;}
Output:
1 2 3 4 5 6 7 8 9 10 

The above code restricts the number of loop iterations to 10.
Apart from this, break can be used in Switch case statements too.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C Basics
CPP-Basics
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Different methods to reverse a string in C/C++
Core Dump (Segmentation fault) in C/C++
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Socket Programming in C/C++
Map in C++ Standard Template Library (STL)