In this tutorial you will learn about the C++ Break statement and its application with practical example.
C++ Break Statement
In C++, break statement inside any loop gives you way to break or terminate the execution of loop containing it, and transfers the execution to the next statement following the loop. It is almost always used with if..else construct.
C++ Break Statement Flow Diagram
Syntax:-
1 |
break; |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> using namespace std; int main() { int count = 0; cout<<"W3Adda - C++ Break Statement"; while(count <= 10){ count = count + 1; if(count == 5){ break; } cout<<"\nInside loop "<<count; } cout<<"\nOut of while loop"; return 0; } |
In this above program, the variable count is initialized as 0. Then a while loop is executed as long as the variable count is less than 10. Inside the while loop, the count variable is incremented by 1 with each iteration (count = count + 1). Next, we have an if statement that checks the variable count is equal to 5, if it return TRUE causes loop to break or terminate. Within the loop there is a cout statement that will execute with each iteration of the while loop until the loop breaks. Then, there is a final cout statement outside of the while loop.
When we run this code, our output will be as follows –
Output:-