原文: https://beginnersbook.com/2017/08/cpp-while-loop/

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

while循环的语法

  1. while(condition)
  2. {
  3. statement(s);
  4. }

循环如何工作?

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

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

while循环流程图

C   中的`while`循环 - 图1

C++中的while循环示例

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

输出:

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

无限循环

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

无限循环的一个例子:

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

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

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

  1. #include <iostream>
  2. using namespace std;
  3. int main(){
  4. int arr[]={21,87,15,99, -12};
  5. /* The array index starts with 0, the
  6. * first element of array has 0 index
  7. * and represented as arr[0]
  8. */
  9. int i=0;
  10. while(i<5){
  11. cout<<arr[i]<<endl;
  12. i++;
  13. }
  14. }

输出:

  1. 21
  2. 87
  3. 15
  4. 99
  5. -12