C++ break statement

The break statement is a control structure in C++ that allows you to terminate a loop prematurely, before the specified termination condition is met. The break statement can be used in conjunction with for, while, and do...while loops to prematurely end the execution of the loop. The basic syntax of the break statement is as follows:

1break;

The break statement must be placed inside the loop and can be used to prematurely end the loop when a specific condition is met.

Let's take a look at two examples of the break statement in C++ and their output:

Simple break Statement

1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 for (int i = 1; i <= 10; i++) 7 { 8 if (i == 3) 9 { 10 break; 11 } 12 cout << "Value of i: " << i << endl; 13 } 14 15 return 0; 16}

In the above example, the break statement is used inside the for loop to prematurely end the loop when the value of i is equal to 3. The for loop initializes the value of i to 1 and continues to execute as long as i is less than or equal to 10. The break statement is executed when the value of i is equal to 3, which terminates the for loop and the program continues with the next statement after the loop.

The output will be:

1Value of i: 1 2Value of i: 2

Nested break Statement

1#include <iostream> 2 3using namespace std; 4 5int main() 6{ 7 for (int i = 1; i <= 3; i++) 8 { 9 for (int j = 1; j <= 2; j++) 10 { 11 if (i == 2 && j == 1) 12 { 13 break; 14 } 15 cout << "Value of i: " << i << " and j: " << j << endl; 16 } 17 } 18 19 return 0; 20}

In the above example, the break statement is used inside a nested for loop to prematurely end the inner loop when the value of i is equal to 2 and the value of j is equal to 1. The outer for loop initializes the value of i to 1 and continues to execute as long as i is less than or equal to 3. The inner for loop initializes the value of j to 1 and continues to execute as long as j is less than or equal to 2. The break statement is executed when the value of i is equal to 2 and the value of j is equal to 1, which terminates the inner loop and the program continues with the next iteration of the outer loop.

The output will be:

1Value of i: 1 and j: 1 2Value of i: 1 and j: 2 3Value of i: 2 and j: 1 4Value of i: 3 and j: 1 5Value of i: 3 and j: 2