C++ do...while迴圈



forwhile迴圈不同,forwhile迴圈在迴圈頂部測試迴圈條件,而do...while迴圈在迴圈底部檢查其條件。

do...while迴圈類似於while迴圈,不同之處在於do...while迴圈保證至少執行一次。

語法

C++中do...while迴圈的語法如下:

do {
   statement(s);
} 
while( condition );

請注意,條件表示式出現在迴圈的末尾,因此迴圈中的語句在條件被測試之前執行一次。

如果條件為真,則控制流跳回到do,並且迴圈中的語句再次執行。這個過程重複,直到給定的條件變為假。

流程圖

C++ do...while loop

示例

#include <iostream>
using namespace std;
 
int main () {
   // Local variable declaration:
   int a = 10;

   // do loop execution
   do {
      cout << "value of a: " << a << endl;
      a = a + 1;
   } while( a < 20 );
 
   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
廣告