English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn about C ++statement: break and continue statements. More specifically, what they are, when to use them, and how to use them effectively.
In C ++There are two statements break;, continue; specifically used to change the normal flow of the program.
Sometimes, you want to skip the execution of the loop with a certain test condition, or terminate it immediately without checking the condition.
For example: you want to traverse all65Data of the elderly over the age of 60. Or, you want to find2The first person under the age of 0.
In such cases, you can use a continue; or break; statement.
break; statement will immediately terminate the loop (for,while and do..while loop) and switch statement.
break;
In practice, the break statement is almost always used within conditional statements (if...else) in loops.
C ++The program adds all the numbers entered by the user until the user enters 0.
// C ++The program demonstrates the operation of the break statement #include <iostream> using namespace std; int main() { float number, sum = 0.0; // The test expression is always true while (true) { cout << "Enter a number: "; cin >> number; if (number != 0.0) { sum += number; } else { // If the number equals 0.0, terminate the loop break; } } cout << "Total = " << sum; return 0; }
Output Result
Enter a number: 5 Enter a number: 3.4 Enter a number: 6.7 Enter a number: -4.5 Enter a number: 0 Total = 10.6
In the above program, the test expression is always true.
Prompt the user to enter a number that is stored in the variable number. If the user enters a number that is not 0, that number will be added to sum and stored in sum.
Similarly, prompt the user to enter another number. When the user enters 0, the test expression in the if statement is false, and the body of the else is executed, terminating the loop.
Finally, display the total.
Sometimes it is necessary to skip certain test conditions within a loop. In this case, continue; in C ++statement in programming.
continue;
In fact, the continue; statement is almost always used within conditional statements.
C ++The program displays1to10the integer between6and9.
#include <iostream> using namespace std; int main() { for (int i = 1; i <= 10; ++i) { if ( i == 6 || i == 9) { continue; } cout << i << "\t"; } return 0; }Output Result
1 2 3 4 5 7 8 10
In the above program, when i is6or9Use the continue; statement to skip, and execute within the loop under other conditions: cout << i << "\t".