While迴圈

本页使用了标题或全文手工转换
维基百科,自由的百科全书
(重定向自While循环

程式語言中,While迴圈(英語:while loop)是一種控制流程陳述。利用一個返回結果為布林值(Boolean)的表達式作為循環條件,當這個表達式的返回值為“真”(true)時,則反覆執行迴圈內的程式碼;若表達式的返回值為“假”(false),則結束執行迴圈內的代碼,繼續執行迴圈下面的代碼。

因為While迴圈在區塊內代碼被執行之前,先檢查陳述是否成立,因此這種控制流程通常被稱為是一種前測試迴圈(pre-test loop)。相對而言Do While迴圈,是在迴圈區塊執行結束之後,再去檢查陳述是否成立,被稱為是後測試迴圈。

程式範例[编辑]

while 迴圈

VB[编辑]

'這是一個用While迴圈的例子
dim counter as Integer
dim Tick as Integer
counter=5
tick=1
Print "Start"
while counter>0
counter=counter-tick
'迴圈語句
Wend
Print "End"


C/C++[编辑]

unsigned int counter = 5;
unsigned long factorial = 1;

while (counter > 0)
{
  factorial *= counter--;    /*當滿足迴圈條件(本例為:counter > 0)時會反覆執行該條語句 */
} 

printf("%lu", factorial);


Java[编辑]

public static void main(str args[]){
    while true{
        System.out.println("Hello World!") //因為條件已經固定為常量true,所以就會不斷執行迴圈內的語句
    }
    int counter = 0 ;
    while counter<5{
        System.out.println("已經運行了"+counter+"次")  //因為條件限定為counter不大於5,所以在counter不大於5的情況下會不斷重複迴圈中的内容
        counter++;
    }
}


Python語言[编辑]

a = 0
while a <= 10 :   #如果a沒有大於10就執行
    a = a+1
    print(a)


另见[编辑]