C++ break Statement

The break statement in C++ is used to terminate loops and switch statement immediately when it appears. We sometimes want to terminate the loop immediately without checking the condition expression of loop. Most of the time, break statement is used with conditional statement inside body of the loop.

Use of break statement, change the normal sequence of execution of statements inside loop.

Syntax of break Statement

break;
C++ Break Statement Control Flow Diagram

Uses of break Statement

  • We can use break statement inside any loop(for, while and do-while). It terminates the loop immediately and program control resumes at the next statement following the loop.
  • We can use break statement to terminate a case in the switch statement.
  • It can be used to end an infinite loop.
  • If we are using break statement inside nested loop, then it will only terminate the inner loop from where break is executed.

C++ break Statement Example Program

#include <iostream>
using namespace std;
 
int main(){

    int N, counter, sum=0;
    cout<< "Enter a positive number\n";
    cin >> N;
     
    for(counter=1; counter <= N; counter++){
        sum+= counter;
        /* If sum is greater than 50 break
           statement will terminate the loop */
        if(sum > 50){
            cout << "Sum is > 50, terminating loop\n";
            // Using break statement to terminate for loop
            break;
        }
    }
    if(counter > N)
        cout << "Sum of Integers from 1 to " << N <<" = "<< sum;
     
    return 0;
}

Output
Enter a positive number
20
Sum is > 50, terminating loop
Enter a positive number
7
Sum of Integers from 1 to 7 = 28
Above program find sum of all integers from 1 to N, using for loop. It sum is greater than 50, break statement will terminate for loop.