C++ Tutorial C++ Advanced C++ References

C++ - Break Statement



The break statement in C++ is used to terminate the program out of the loop containing it whenever the condition is met.

If the break statement is used in a nested loop (loop inside loop), it will terminate innermost loop after fulfilling the break criteria.

Break statement with While loop

In the example below, break statement is used to get out of the while loop if the value of variable j becomes 4.

#include <iostream>
using namespace std;
 
int main (){
  int j = 0;
  while (j < 10){
    j++;
    if(j == 4){
      cout<<"Getting out of the loop.\n"; 
      break;
    }
    cout<<j<<"\n"; 
  }
  return 0;
}

The output of the above code will be:

1
2
3
Getting out of the loop.

Break statement with For loop

Here, the break statement is used to get out of the for loop if the value of variable i becomes 4.

#include <iostream>
using namespace std;
 
int main (){
  for (int i = 1; i <= 6; i++){
    if(i == 4){
      cout<<"Getting out of the loop.\n"; 
      break;
    }
    cout<<i<<"\n"; 
  }
  return 0;
}

The output of the above code will be:

1
2
3
Getting out of the loop.

Break statement with Nested loop

The Break statement terminates the inner loop whenever condition is fulfilled. In below mentioned example, program terminates the inner loop only when j = 100 (resulting the program to skip the inner loop for j = 100 and 1000).

//Nested loop without break statement
#include <iostream>
using namespace std;
 
int main (){
  cout<<"# Nested loop without break statement\n"; 
  for (int i = 1; i <= 3; i++){
    for (int j = 10; j <= 1000; j = j * 10){
      cout<<i*j<<"\n"; 
    }
  }
  return 0;
}

The output of the above code will be:

# Nested loop without break statement
10
100
1000
20
200
2000
30
300
3000

//Nested loop with break statement
#include <iostream>
using namespace std;
 
int main (){
  cout<<"# Nested loop with break statement\n";  
  for (int i = 1; i <= 3; i++){
    for (int j = 10; j <= 1000; j = j * 10){
      if(j == 100 ){
        break;
      }
      cout<<i*j<<"\n"; 
    }
  }
  return 0;
}

The output of the above code will be:

# Nested loop with break statement
10
20
30