💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# C++ 中的`do-while`循环 > 原文: [https://beginnersbook.com/2017/08/cpp-do-while-loop/](https://beginnersbook.com/2017/08/cpp-do-while-loop/) 正如上一篇关于[`while`循环](https://beginnersbook.com/2017/08/cpp-while-loop/)的教程中所讨论的,循环用于重复一个语句块,直到给定的循环条件返回`false`。在本教程中,我们将看到`do-while`循环。`do-while`循环类似于`while`循环,但它们之间存在差异:在`while`循环中,首先计算条件,然后执行循环体内的语句,另一方面在`do-while`循环中执行 - 首先执行,然后求值条件。 #### `do-while`循环的语法 ```cpp do { statement(s); } while(condition); ``` ## `do-while`循环如何工作? 首先,循环内的语句执行,然后条件得到求值,如果条件返回`true`,则控制跳转到`do`以进一步重复执行它,这会重复发生,直到条件返回`false`。一旦条件返回`false`,控制就会跳转到程序中`do-while`之后的下一个语句。 ![C++ do while loop flow diagram](https://img.kancloud.cn/c5/33/c533f6827cfa61e8d65e460440677b4e_400x400.jpg) ## C++ 中的`do-while`循环示例 ```cpp #include <iostream> using namespace std; int main(){ int num=1; do{ cout<<"Value of num: "<<num<<endl; num++; }while(num<=6); return 0; } ``` **输出:** ```cpp Value of num: 1 Value of num: 2 Value of num: 3 Value of num: 4 Value of num: 5 Value of num: 6 ``` ## 示例:使用`do-while`循环显示数组元素 这里我们有一个整数数组,它有四个元素。我们使用`do-while`循环显示它的元素。 ```cpp #include <iostream> using namespace std; int main(){ int arr[]={21,99,15,109}; /* Array index starts with 0, which * means the first element of array * is at index 0, arr[0] */ int i=0; do{ cout<<arr[i]<<endl; i++; }while(i<4); return 0; } ``` **输出:** ```cpp 21 99 15 109 ```