在C++中,while循环用于重复程序的一部分几次(或多次)。 如果迭代次数不固定,建议使用while循环而不是for
循环。
下面是while循环的语法 -
while(condition){
//code to be executed
}
while循环的执行流程图-
C++ while循环示例
下面来看看下面一个简单的例子,使用while
循环打印从1
到10
的数字。
#include <iostream>
using namespace std
int main() {
int i=1
while(i<=10)
{
cout<<i <<"\n"
i++
}
return 0
}
执行上面代码,得到以下结果 -
[yiibai@localhost cpp]$ g++ while.cpp && ./a.out
1
2
3
4
5
6
7
8
9
10
[yiibai@localhost cpp]$
C++嵌套While循环示例
在C++中,可以在另一个while循环中使用while循环,它被称为嵌套while循环。执行一次外部循环时,嵌套while循环完全执行。
下面来看看一个在C++编程语言中嵌套while循环的简单例子。
#include <iostream>
using namespace std
int main () {
int i=1
while(i<=3)
{
int j = 1
while (j <= 3)
{
cout<<i<<" "<<j<<"\n"
j++
}
i++
}
return 0
}
执行上面代码,得到以下结果 -
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
C++无限循环示例:
还可以通过传递true
作为测试条件,来创建无限while循环。
#include <iostream>
using namespace std
int main () {
while(true)
{
cout<<"Infinitive While Loop"
}
return 0
}
执行上面代码,得到以下结果 -
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
ctrl+c