Presentation is loading. Please wait.

Presentation is loading. Please wait.

While 迴圈 - 不知重複執行次數 01010 10101 01010 10101 01010 10101 01010.

Similar presentations


Presentation on theme: "While 迴圈 - 不知重複執行次數 01010 10101 01010 10101 01010 10101 01010."— Presentation transcript:

1 While 迴圈 - 不知重複執行次數 01010 10101 01010 10101 01010 10101 01010

2 重複結構 依條件決定是否重複執行某些敘述 for 巢狀 for while do...while

3 前測式重複結構 -while 使用時機  for 迴圈 重複執行次數可預先確定  while 迴圈 1. 迴圈重複執行次數無法預先確定 2. 不知道迴圈何時結束,但可設定條件 ( 測試條件 ) 加 以控制

4 while 迴圈 流程圖 true false 重複程式區塊 改變測試條件變數 測試條件 測試條件變數初始化

5 前測式重複結構 -while 語法 測試條件變數初始化 ; while ( 測試條件 ) { 程式敘述 ; … 改變測試條件變數 ; } … 1. 先判斷測試條件之真假,若為真則進入迴圈內 2. 執行迴圈內敘述,改變測試條件變數 3. 重複步驟 1 , 2 直到判斷測試條件為假,離開迴圈。執行 迴圈外第一行 需改變測試條件 否則程式進入無 窮迴圈 因此叫前測 start end 迴圈外第一行

6 sum=0 i=1 從 1 累加正整數到多少,累加的值會大於 300? ( 用 while 迴圈 ) # include int main() { int i=1,sum=0; while(sum<=300) { sum += i; i++; } printf(" 從 1 累加到 %d ,累加的值會大於 300\n",i-1); system("pause"); return 0; } 為什麼是 i-1 ? i=16 時,sum<=300, 將 16 加入 sum,i++(i=17) i=17 時,sum>300, 離開迴圈, 執行 printf 2 3 4 1 3 6 Yes …1+…+16 16 Yes 17 No 使程式暫停在執行畫面讓我們看到結果 i=i+1; sum=sum+i; sum<=300 sum i

7 1342 #include int main() { int a,b; printf(" 請輸入一個正整數 (1~9999):"); scanf("%d",&a); while (a>0) { b= a%10; printf("%d",b); a= a/10; } system("PAUSE"); return 0; } 使用者輸入一個小於 10000 的正整數後,將這個數字倒著列印出來,例如輸 入 1342 ,輸出 2431 數字倒轉 取得個位數 去掉個位數的值, ex: 1342 -> 134 2134 4 13 3 1 1 0 2 431 Yes No a>0 a b 輸出


Download ppt "While 迴圈 - 不知重複執行次數 01010 10101 01010 10101 01010 10101 01010."

Similar presentations


Ads by Google