C++ break statement



In C++ break statement is used for the termination of the loop statement and switch case statement. Below is the syntax of the break statement.

break;

#1. C++ Break Statement Example :

Example of the break statement is used below –

#include <iostream>
using namespace std;
 
int main ()
{
   // Declaring Local variable
   int count = 0;

   // do loop execution
   do
   {
       cout << "Count : " << count << endl;
       count++;
       if( count > 5)
       {
          // Terminate the loop
          break;
       }
   }while( count < 20 );
 
   return 0;
}

Output :

Count : 0
Count : 1
Count : 2
Count : 3
Count : 4
Count : 5

Explanation :

In the above example, while condition specified that, loop will iterate 20 times.

while( count < 20 )

Now in the loop body we have written the simple condition which tells us to break the loop if the count value becomes greater than 5.

if( count > 5)
{
  // Terminate the loop
  break;
}

#2. C++ Break Statement in nested loop Example :

If we are using the nested loop and we used break statement in the inner loop then break will terminate the inner loop.

do
{	
   for(int i=0; i<5; i++) {
       cout << i;
       if(i == 1)
         break;
   }
   
   cout << "Count : " << count << endl;
   count++;

}while( count < 20 );

In the above example, outer loop will be executed as usual, but the inner loop will be terminated as soon as the value of i becomes 1.

Flow diagram :