📜  C++ break语句

📅  最后修改于: 2020-09-25 04:45:55             🧑  作者: Mango

###### 在本教程中，我们将在示例的帮助下了解break语句及其在循环中的工作。

`break`语句的语法为：

``break;``

#### 示例1：使用for循环中断

``````// program to print the value of i

#include
using namespace std;

int main() {
for (int i = 1; i <= 5; i++) {
// break condition
if (i == 3) {
break;
}
cout << i << endl;
}

return 0;
}``````

``````1
2``````

``````if (i == 3) {
break;
}``````

#### 示例2：使用while循环中断

``````// 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
using namespace std;

int main() {
int number;
int sum = 0;

while (true) {
// take input from the user
cout << "Enter a number: ";
cin >> number;

// break condition
if (number < 0) {
break;
}

sum += number;
}

// display the sum
cout << "The sum is " << sum << endl;

return 0;
}``````

``````Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: -5
The sum is 6. ``````

``````if(number < 0) {
break;
}``````

`while`循环继续进行，直到用户输入一个负数。

#### 打破嵌套循环

`break`与嵌套循环一起使用时， `break`终止内部循环。例如，

``````// using break statement inside
// nested for loop

#include
using namespace std;

int main() {
int number;
int sum = 0;

// nested for loops

// first loop
for (int i = 1; i <= 3; i++) {
// second loop
for (int j = 1; j <= 3; j++) {
if (i == 2) {
break;
}
cout << "i = " << i << ", j = " << j << endl;
}
}

return 0;
}``````

``````i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3``````

`break`语句也与`switch`语句一起使用。要了解更多信息，请访问C++ switch语句。