💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# C++ 中的`for`循环 > 原文: [https://beginnersbook.com/2017/08/cpp-for-loop/](https://beginnersbook.com/2017/08/cpp-for-loop/) 循环用于重复执行语句块,直到满足特定条件。例如,当您显示从 1 到 100 的数字时,您可能希望将变量的值设置为 1 并将其显示 100 次,在每次循环迭代时将其值增加 1。 在 C++ 中,我们有三种类型的基本循环:`for`,[`while`](https://beginnersbook.com/2017/08/cpp-while-loop/)和[`do-while`](https://beginnersbook.com/2017/08/cpp-do-while-loop/) 。在本教程中,我们将学习如何在 C++ 中使用`for` 循环。 #### `for`循环的语法 ```cpp for(initialization; condition ; increment/decrement) { C++ statement(s); } ``` ## `for`循环的执行流程 当程序执行时,解释器总是跟踪将要执行的语句。我们将其称为控制流程或程序的执行流程。 ![C++ for loop flow diagram](https://img.kancloud.cn/3e/65/3e657bb9c43403711b5bff436dad0453_400x400.jpg) **第一步:**在`for`循环中,初始化只发生一次,这意味着`for`循环的初始化部分只执行一次。 **第二步:** `for`循环中的条件在每次循环迭代时进行计算,如果条件为真,则`for`循环体内的语句将被执行。一旦条件返回`false`,`for`循环中的语句就不会执行,并且控制被转移到程序中`for`循环后的下一个语句。 **第三步:**每次执行`for`循环体后,`for`循环的递增/递减部分更新循环计数器。 **第四步:**第三步后,控制跳转到第二步,重新求值条件。 > 从第二到第四的步骤重复,直到循环条件返回`false`。 ## C++ 中的简单`for`循环示例 这里,在循环初始化部分中,将变量`i`的值设置为 1,条件是`i <= 6`,并且在每次循环迭代中,`i`的值递增 1。 ```cpp #include <iostream> using namespace std; int main(){ for(int i=1; i<=6; i++){ /* This statement would be executed * repeatedly until the condition * i<=6 returns false. */ cout<<"Value of variable i is: "<<i<<endl; } return 0; } ``` **输出:** ```cpp Value of variable i is: 1 Value of variable i is: 2 Value of variable i is: 3 Value of variable i is: 4 Value of variable i is: 5 Value of variable i is: 6 ``` ## C++ 中的无限循环 当循环重复执行并且永不停止时,循环被认为是无限的。这通常是错误的。当你在`for`循环中设置条件时它永远不会返回`false`,它就会变成无限循环。 **例如:** ```cpp #include <iostream> using namespace std; int main(){ for(int i=1; i>=1; i++){ cout<<"Value of variable i is: "<<i<<endl; } return 0; } ``` 这是一个无限循环,因为我们递增`i`的值,因此它总是满足条件`i <= 1`,条件永远不会返回`false`。 这是无限`for`循环的另一个例子: ```cpp // infinite loop for ( ; ; ) { // statement(s) } ``` ## 示例:使用`for`循环显示数组元素 ```cpp #include <iostream> using namespace std; int main(){ int arr[]={21,9,56,99, 202}; /* We have set the value of variable i * to 0 as the array index starts with 0 * which means the first element of array * starts with zero index. */ for(int i=0; i<5; i++){ cout<<arr[i]<<endl; } return 0; } ``` **输出:** ```cpp 21 9 56 99 202 ```