break and continue Statement in C++

 Break and Continue Statement in C++


 break and continue Statement in C++
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: You want to loop through data of all aged people except people aged 65. Or, you want to find the first person aged 20.
In scenarios like these, continue; or a break; statement is used.

C++ break Statement

The break; statement terminates a loop (forwhile 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?

Working of break statement in C++ programming

Example 1: C++ break

C++ program to add all number entered by user until user enters 0.
  1. // C++ Program to demonstrate working of break statement
  2. #include <iostream>
  3. using namespace std;
  4. int main() {
  5. float number, sum = 0.0;
  6. // test expression is always true
  7. while (true)
  8. {
  9. cout << "Enter a number: ";
  10. cin >> number;
  11. if (number != 0.0)
  12. {
  13. sum += number;
  14. }
  15. else
  16. {
  17. // terminates the loop if number equals 0.0
  18. break;
  19. }
  20. }
  21. cout << "Sum = " << sum;
  22. return 0;
  23. }
Output
Enter a number: 4
Enter a number: 3.4
Enter a number: 6.7
Enter a number: -4.5
Enter a number: 0
Sum = 9.6
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 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.

C++ continue Statement

It is sometimes necessary to skip a certain test condition within a loop. In such case, continue; statement is used in C++ programming.

Syntax of continue

continue;
In practice, continue; statement is almost always used inside a conditional statement.

Working of continue Statement

Working of continue statement in C++ programming

Example 2: C++ continue

C++ program to display integer from 1 to 10 except 6 and 9.
  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. for (int i = 1; i <= 10; ++i)
  6. {
  7. if ( i == 6 || i == 9)
  8. {
  9. continue;
  10. }
  11. cout << i << "\t";
  12. }
  13. return 0;
  14. }
Output
1 2 3 4 5      7 8 10 
In above program, when i is 6 or 9, execution of statement cout << i << "\t"; is skipped inside the loop using continue; statement.

Comments

Popular posts from this blog

C++ Templates ?

C++ Program to Print Number Entered by User

Educational Website