In this article, we are going to learn about break statement.
The break Statement is very popular among the loop and plays a very crucial role. Break Statement simply means end or termination of the loop before completing the normal life of loop. Here normal life of the loop means ending of loop after checking all the conditions.
Here are two important points on break :
break;
statement can be used in the body of the loop or in switch
body.
Other then that there is no usage of break.
break;
statement is to terminate the execution of the loop immediately
The syntax of the break
statement in C++ is:
break;
Now , before understanding the break statement one should be known to the following topics:
Flowchart of break statement
Understanding break using for loop
// program to print the value of i #include <iostream> using namespace std; int main() { for (int i = 1; i <= 10; i++) { // break condition if (i == 5) { break; } cout << i << endl; } return 0; }
Output :
1 2 3 4
In the above program, the for loop is used to print the value of i
in each iteration.
if (i == 5) { break; }
This means, when i
is equal to 5, the break statement
terminates the loop. Hence, the output doesn't include values greater than or equal to
5.
Understanding break with while loop
// program to find the sum of positive numbers // if the user enters a negative numbers, break ends the loop // the negative number entered is not added to sum #include <iostream> using namespace std; int main(){ int num; int sum = 0; while (true) { // take input from the user cout << "Enter value: "; cin >> num; // break condition if (num < 0) { break; } // add all positive numbers sum += num; } // display the sum cout << "Sum is " << sum << endl; return 0; }
Output :
Enter value: 5 Enter value: 10 Enter value: 15 Enter value: -2 Sum is 30.
In the above program, the user enters a number. The while loop is used to print the total sum of numbers entered by the user. Here, notice the code :
if(num < 0) { break; }
This means, when the user enters a negative number, the break
statement terminates the loop
and codes outside the loop are executed.
The while
loop continues until the user enters a negative number.
Understanding break with Nested loop
When break is used with nested loops, break terminates the inner loop. For example :
// using break statement inside // nested for loop #include <iostream> using namespace std; int main() { int num; int sum = 0; // nested for loops // first loop for (int i = 5; i <= 10; i++) { // second loop for (int j = 5; j <= 10; j++) { if (i == 6) { break; } cout << "i = " << i << ", j = " << j << endl; } } return 0; }
Output :
i = 5, j = 5 i = 5, j = 5 i = 5, j = 5 i = 7, j = 5 i = 7, j = 6 i = 7, j = 7
In the above program, the break statement is executed when i == 2
. It
terminates the inner loop, and the control flow of the program moves to the outer loop.
Hence, the value of i = 6
is never displayed in the output.