while 迴圈
當我們要執行重複的指令時,一直不斷複製相同的程式碼會很占版面,而迴圈就能幫助我們處理這種狀況。
基本架構
條件句如果出錯,迴圈就可能會變成無窮迴圈,無法停下。
e.g. 當判斷條件為while(1)時,因為 1 永遠是 true ,所以迴圈會無限循環
每一輪迴圈開始跑之前,才會檢查條件是否符合,因此途中不符合仍然會持續運作
範例 1
試著印出 1~5 吧
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
使用 while:
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
因為想要執行重複輸出這個動作,所以使用迴圈並設定一個 i 變數,當 i <= 5 時輸出 i,因為 i = 1,如果想每次輸出的數字都往上加 1,就要再放一個 i++;
的指令或是 i+=1;
,表示 i=i+1
範例 2
重複輸入某數,如果它小於 3,輸出它加 3 的結果,如果大於 3,輸出它乘 3 的結果
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
在不知道執行次數,但知道何種條件下要終止迴圈時,可以使用 while,但一定要注意的是 return 0;
不能放在迴圈裡面,否則只會執行一次,因為沒有處理 num == 3 的情況,所以不會輸出任何東西
do while
和 while 相比,while 是先判斷條件是否成立,再執行程式,而 do while 則是先執行程式,再去判斷條件是否成立
透過下方的例子,可以更明顯的知道兩者的不同:
while
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
do while

使用 do while 時,務必記得在 while() 後要加上 ;
但 while 只要做一下處理,也能達到和 do while 一樣的結果,不用特別去記 do while 的用法也沒關係