D 程式設計 - Do...While 迴圈



forwhile迴圈不同,它們在迴圈頂部測試迴圈條件,D 程式語言中的do...while迴圈在迴圈底部檢查其條件。

do...while迴圈類似於while迴圈,但do...while迴圈至少執行一次。

語法

D 程式語言中do...while迴圈的語法為

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

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

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

流程圖

do...while loop in D

示例

import std.stdio;

int main () {
   /* local variable definition */
   int a = 10;

   /* do loop execution */
   do{
      writefln("value of a: %d", a);
      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
d_programming_loops.htm
廣告