目录

while循环

只要给定条件为真, while循环语句就会重复执行目标语句。

语法 (Syntax)

C ++中while循环的语法是 -

while(condition) {
   statement(s);
}

这里, statement(s)可以是单个语句或语句块。 condition可以是任何表达式,true是任何非零值。 当条件为真时,循环迭代。

当条件变为假时,程序控制将立即传递到循环之后的行。

流程图 (Flow Diagram)

C ++ while循环

这里, while循环的关键点是循环可能永远不会运行。 当测试条件并且结果为假时,将跳过循环体并且将执行while循环之后的第一个语句。

例子 (Example)

#include <iostream>
using namespace std;
int main () {
   // Local variable declaration:
   int a = 10;
   // while loop execution
   while( a < 20 ) {
      cout << "value of a: " << a << endl;
      a++;
   }
   return 0;
}

编译并执行上述代码时,会产生以下结果 -

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
↑回到顶部↑
WIKI教程 @2018