跳去內容

Do-while 迴圈

出自維基百科,自由嘅百科全書
Do-while 迴圈嘅活動圖

Do-while 迴圈係同 while 迴圈好相似嘅迴圈,分別在於幾時評估個條件:Do-while 迴圈都係會有條件,同埋一柞掕住嘅碼。個程式會行一次段掕住碼,睇吓個條件係咪真,如果係,噉就再行多次段掕住碼,跟住再睇吓個條件係咪真,如此類推。喺一個程式嘅執行過程當中,一個 do-while 迴圈起碼會行一次,而一個 while 迴圈有機會可以完全一次都唔行,所以 do-while 迴圈有陣時可以做啲 while 迴圈做唔到嘅效果,不過有好多受歡迎嘅程式語言都冇 do-while 迴圈[1]

某啲語言可能會有類似但係條件相反嘅流程控制,可以叫 Repeat-until 迴圈;佢同 Do-while 迴圈一樣,都係行咗迴圈入面嘅碼先,但係跟住嘅條件係終止條件,如果係真就離開迴圈[2]。有 Repeat-until 迴圈嘅語言包括 PascalLua 同某一啲嘅 BASIC

應用例子

[編輯]

以下呢段 Java 碼就用咗 do-while 迴圈[3]

public class DoWhileExample {  
public static void main(String[] args) {  
    int i = 1; // 設 i 嘅數值係 1。  
    do{  
        System.out.println(i); // 騷出 i 嘅數值。
    i++;  // 將 i 嘅數值上升 1。
    }while(i <= 10);  // do {} 入面嘅碼 while i 細過或者等如 10。
}  
} // 呢段碼會將 1 到 10 嘅數字 show 喺 output 嗰度。

參考資料

[編輯]
  1. Python Do While Loop 互聯網檔案館歸檔,歸檔日期2019年9月5號,..
  2. "Condition controlled iteration". Programming concepts - AQA (英國英文). BBC. 喺2025年4月9號搵到.
  3. Java do-while Loop 互聯網檔案館歸檔,歸檔日期2019年9月5號,..