C++ break Statement
C++ break Statement
In C++, there are two statements break; and continue; specifically to alter the normal flow of a program.
Sometimes, it is desirable to skip the execution of a loop for a certain test condition or terminate it immediately without checking the condition.
For example : Yoy want to loop through data of all aged people except people aged 65. Or you wnat to find the person aged 20.
In Scenarios like these , continue; or a break; statement is used.
C++ break Statement
The break; statement terminates a loop (for, while and do while loop) and a switch statement immediately when it appears.
Syntax of break
break;
In real practice, break statement is almost always used inside the body of conditional statement (if... else) inside the loop.
How break statement works?
Example : C++ break
C++ program to add all number entered by user until user enters 0
Output
In the above program, the test expression is always true.
The user is asked to enter a number which is stored in the variable number. if the user enters any number other than 0, the number is added to sum and stored to it.
Again, the user is asked to enter another number. When the user enters 0, the test expression inside if statement is false and body of else is executed which terminates the loop.
Finally, the sum is displayed.
0 comments:
Post a Comment