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

循环用于重复执行语句块,直到满足特定条件。例如,当您显示从 1 到 100 的数字时,您可能希望将变量的值设置为 1 并将其显示 100 次,在每次循环迭代时将其值增加 1。

在 C++ 中,我们有三种类型的基本循环:forwhiledo-while 。在本教程中,我们将学习如何在 C++ 中使用for 循环。

for循环的语法

  1. for(initialization; condition ; increment/decrement)
  2. {
  3. C++ statement(s);
  4. }

for循环的执行流程

当程序执行时,解释器总是跟踪将要执行的语句。我们将其称为控制流程或程序的执行流程。

C   中的`for`循环 - 图1

第一步:for循环中,初始化只发生一次,这意味着for循环的初始化部分只执行一次。

第二步: for循环中的条件在每次循环迭代时进行计算,如果条件为真,则for循环体内的语句将被执行。一旦条件返回falsefor循环中的语句就不会执行,并且控制被转移到程序中for循环后的下一个语句。

第三步:每次执行for循环体后,for循环的递增/递减部分更新循环计数器。

第四步:第三步后,控制跳转到第二步,重新求值条件。

从第二到第四的步骤重复,直到循环条件返回false

C++ 中的简单for循环示例

这里,在循环初始化部分中,将变量i的值设置为 1,条件是i <= 6,并且在每次循环迭代中,i的值递增 1。

  1. #include <iostream>
  2. using namespace std;
  3. int main(){
  4. for(int i=1; i<=6; i++){
  5. /* This statement would be executed
  6. * repeatedly until the condition
  7. * i<=6 returns false.
  8. */
  9. cout<<"Value of variable i is: "<<i<<endl;
  10. }
  11. return 0;
  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

C++ 中的无限循环

当循环重复执行并且永不停止时,循环被认为是无限的。这通常是错误的。当你在for循环中设置条件时它永远不会返回false,它就会变成无限循环。

例如:

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

这是一个无限循环,因为我们递增i的值,因此它总是满足条件i <= 1,条件永远不会返回false

这是无限for循环的另一个例子:

  1. // infinite loop
  2. for ( ; ; ) {
  3. // statement(s)
  4. }

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

  1. #include <iostream>
  2. using namespace std;
  3. int main(){
  4. int arr[]={21,9,56,99, 202};
  5. /* We have set the value of variable i
  6. * to 0 as the array index starts with 0
  7. * which means the first element of array
  8. * starts with zero index.
  9. */
  10. for(int i=0; i<5; i++){
  11. cout<<arr[i]<<endl;
  12. }
  13. return 0;
  14. }

输出:

  1. 21
  2. 9
  3. 56
  4. 99
  5. 202