以下是C ++中可用的循环语句列表
- While循环
- 做.. while循环
- 对于循环
- 打破
- 继续
- 嵌套循环
当我们想一次又一次地重复同一组语句时,使用循环语句。这些语句集将一直执行到满足特定条件为止。下面我们用简单的示例讨论各种类型的循环结构。
1. While循环语句
句法:
while (test_condition) { //statements }
while循环工作:
- 评估测试条件,如果为true,则执行while块中的语句。
- 在执行中,更新变量,然后再次检查条件。
- 如果测试条件失败,它将退出循环。
- while语句末尾没有分号。
“ while”循环的示例。
#include<iostream> using namespace std; int main() { int j = 0; int count = 2; while (j < count) { cout<<" J = "<<j << endl; j++;// don’t forget to increment. Otherwise it will become infinite loop } return 0; }
输出量:
J = 0 J = 1
2.执行.. while循环语句
句法:
do { //statements } while (test_condition);
do .. while循环的工作:
- 确保do .. while语句内的所有语句执行一次。
- 退出循环时检查条件。
- 注意while()语句末尾的分号。
“ do .. while”循环的示例:
#include<iostream> using namespace std; int main() { int j = 0; int count = 2; { cout<<" J = "<<j << endl; j++;// dont forget to increment. Otherwise it will become infinate loop }while (j == 2) // Condition is false, but statements are executed atleast 上 ce. return 0; }
输出量
J = 0
3. For循环语句
像许多语言一样,C ++也提供for循环。 C ++为循环提供了更大的灵活性,我们将在程序示例中进行介绍。
下面是语法。
for(initialization; condition-checking; increment/decrement) { //statements }
要记住的要点:
- for循环语法的末尾没有分号。
- 初始化仅执行一次。
- 然后它将检查条件,如果为true,则将执行语句,然后增加值。
- 可以有多个条件和增量/减量语句。
- 也可以在for循环外进行初始化。
显示for循环变体的示例:
#include<iostream> using namespace std; int main() { int j = 0; int count = 5; for (int i = 0; i < count; ++i) { cout<<i<<endl; } for(; ; ) // initialization is done 上 top { if (j == 5) // condition is checked here cout << "J is 5"<<endl; j++; // incremented here } for( ; ; ) //infinite for loop { // dangerous!! // your program will run indefinitely } return 0; }
4.中断声明
打破语句用于退出循环。遇到这种情况时,将执行循环后的语句。如果在内循环中有一个break语句,则它将进入外循环。
break语句示例:
#include<iostream> using namespace std; int main() { int j = 0; int count = 5; while (j < count) { cout<<" J = "<<j << endl; j++; if ( j == 3) break; // it will come out of the loop, when j is 3 } return 0; }
输出:
J = 0 J = 1 J = 2
5.继续声明
“ continue”类似于break,但不是跳出循环,而是跳过当前迭代并继续下一个迭代。
继续声明的示例:
#include<iostream> using namespace std; int main() { int j = 0; int count = 5; while (j < count) { j++; if ( j == 3) continue; // when j is 3, it will skip execution cout<<" J = "<<j << endl; } return 0; }
输出:
J = 1 J = 2 J = 4 J = 5
6.嵌套循环
一个循环可以在另一个循环内。然后称为嵌套循环。
嵌套循环示例
#include<iostream> using namespace std; int main() { int j = 1; int count = 3; for (int i = 0; i < count; i++) { j = i+1; while (j < count) { cout<<"I = "<< i<<" J = "<<j << endl; j = j + 1; } } return 0; }
输出:
I = 0 J = 1 I = 0 J = 2 I = 1 J = 2
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |