C++ while循环

来源:这里教程网 时间:2026-02-16 16:04:35 作者:

在上一篇教程中,我们讨论了for循环 。在本教程中,我们将讨论while循环。如前所述,循环用于重复执行程序语句块,直到给定的循环条件返回false。

while循环的语法

while(condition){   statement(s);}

循环如何工作?

在while循环中,首先计算条件,如果它返回true,则执行while循环中的语句,这会重复发生,直到条件返回false。当条件返回false时,控制流退出循环并跳转到程序中的while循环后的下一个语句。

注意:使用while循环时要注意的重点是,我们需要在while循环中使用递增或递减语句,以便循环变量在每次迭代时都会发生变化,并且在某些情况下返回false。这样我们就可以结束while循环的执行,否则循环将无限期地执行。

while循环流程图

C++ while循环

C++中的while循环示例

#include <iostream>using namespace std;int main(){   int i=1;   /* The loop would continue to print    * the value of i until the given condition    * i<=6 returns false.    */   while(i<=6){      cout<<"Value of variable i is: "<<i<<endl; i++;   }}

输出:

Value of variable i is: 1Value of variable i is: 2Value of variable i is: 3Value of variable i is: 4Value of variable i is: 5Value of variable i is: 6

无限循环

永远不停止的while循环被认为是无限循环,当我们以这样的方式给出条件,以使它永远不会返回false时,循环变为无限并且无限地重复。

无限循环的一个例子:

这个循环永远不会结束,因为我从 1 开始递减i的值,因此条件i <= 6永远不会返回false。

#include <iostream>using namespace std;int main(){   int i=1; while(i<=6) {      cout<<"Value of variable i is: "<<i<<endl; i--;   }}

示例:使用while循环显示数组元素

#include <iostream>using namespace std;int main(){   int arr[]={21,87,15,99, -12};   /* The array index starts with 0, the    * first element of array has 0 index    * and represented as arr[0]    */   int i=0;   while(i<5){      cout<<arr[i]<<endl;      i++;   }}

输出:

21871599-12

相关推荐