tags: tgirc早修book

while 迴圈

當我們要執行重複的指令時,一直不斷複製相同的程式碼會很占版面,而迴圈就能幫助我們處理這種狀況。

基本架構

#include <iostream> using namespace std; int main(){ while(條件句) { 循環指令; } return 0; }

條件句如果出錯,迴圈就可能會變成無窮迴圈,無法停下。
e.g. 當判斷條件為while(1)時,因為 1 永遠是 true ,所以迴圈會無限循環

每一輪迴圈開始跑之前,才會檢查條件是否符合,因此途中不符合仍然會持續運作

範例 1
試著印出 1~5 吧

#include <iostream> using namespace std; int main(){ cout<<"1\n"; cout<<"2\n"; cout<<"3"<<"\n"; cout<<4<<"\n"; cout<<5<<"\n"; return 0; }

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

#include <iostream> using namespace std; int main(){ int i=1; while(i<=5){ cout<<i<<"\n"; i++; //i=i+1 } return 0; }

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 的結果

#include <iostream> using namespace std; int main(){ int num; while(cin>>num){ if(num<3){ cout<<"num<3 : num+3 = "<<num+3<<"\n"; } else if(num>3){ cout<<"num>3 : num*3 = "<<num*3<<"\n"; } } return 0; }

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 則是先執行程式,再去判斷條件是否成立

#include <iostream> using namespace std; int main(){ do { 循環指令; } while(條件句); return 0; }

透過下方的例子,可以更明顯的知道兩者的不同:

while

#include <iostream> using namespace std; int main(){ int i=0; while(i>0){ i--; //i=i-1 } cout<<i<<"\n"; return 0; }

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

#include <iostream> using namespace std; int main(){ int i=0; do { i--; //i=i-1 } while(i>0); cout<<i<<"\n"; return 0; }

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