1 / 11

C 語言 - 迴圈

C 語言 - 迴圈. 程式基本結構. 循序式結構 程式依第一個敘述執行至最後一個敘述。 選擇式結構 程式含有條件敘述,當條件敘述的條件成立時,執行條件成立區的敘述。 條件敘述 Ex: if, if-else, if-else if, switch 重複式結構 程式含有條件敘述,當條件敘述的條件成立時,執行條件成立區的敘述。 重複敘述 Ex: do-while, while, for goto 結構 將程式流程無條件轉移到標籤位置。. 重複式 結構. for 敘述的流程圖:. 運算式 1. 運算式 2. false. true. 敘述.

eris
Télécharger la présentation

C 語言 - 迴圈

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C語言-迴圈

  2. 程式基本結構 • 循序式結構 • 程式依第一個敘述執行至最後一個敘述。 • 選擇式結構 • 程式含有條件敘述,當條件敘述的條件成立時,執行條件成立區的敘述。 • 條件敘述 Ex: if, if-else, if-else if, switch • 重複式結構 • 程式含有條件敘述,當條件敘述的條件成立時,執行條件成立區的敘述。 • 重複敘述 Ex: do-while, while, for • goto結構 • 將程式流程無條件轉移到標籤位置。

  3. 重複式結構

  4. for敘述的流程圖: 運算式1 運算式2 false true 敘述 Next敘述 運算式3 重複性:for for敘述的語法格式: for(運算式1;運算式2;運算式3) { 敘述區; } 運算式1:迴圈控制變數的初值 運算式2:迴圈是否重覆執行的條件 運算式3:迴圈控制變數的修正值

  5. 程式範例-計算1累加至100的總和,並輸出其總和程式範例-計算1累加至100的總和,並輸出其總和 #include<stdio.h> #include<stdlib.h> int main() { inti , sum=0; /*宣告變數 i、sum為整數*/ for (i=1; i<=100; i++) { sum= sum+i; } printf("sum= %d\n",sum); /*迴圈結束時,印出sum的值*/ system("pause"); return 0; }

  6. 程式範例-無窮for迴路 #include<stdio.h> #include<stdlib.h> intmain() { inti; int count = 0; for ( ; ; ) { printf("guess number here:"); scanf(“%d”,&i); if ( i == 5 ) break; count++; } printf("You take %d times to get it. ", count); system("pause"); return 0; }

  7. while敘述的流程圖: 運算式 false true 敘述 Next敘述 重複性:while while敘述的語法格式: while(運算式) { 敘述區; 迴圈主體; 設定增減量; }

  8. 程式範例-while(1)與switch的應用 #include<stdio.h> intmain() { inti; while(1) { printf("Enter 1-4 for exit "); scanf("%d",&i); switch ( i ) { case 1 : printf("Excellent!\n"); break; case 2 : printf("Good!\n"); break; case 3 : printf("Fair!\n"); break; case 4 : printf("Bye!\n"); break; default: printf("Illegal number ry again!\n"); } if (i==4) break; } system(“pasue"); return 0; }

  9. do while敘述的流程圖: 敘述 true 運算式 false Next敘述 重複性:do while do while敘述的語法格式: do { 敘述區; 迴圈主體; 設定增減量; } while(運算式);

  10. 程式範例-計算總和 #include<stdio.h> intmain() { int a, sump=0; do { printf("請輸入一個整數:"); scanf("%d",&a); if (a>0) sump=sump+a; } while (a!=0); printf("總和= %d\n",sump); system(“pause"); return 0; }

  11. 重複式結構比較 for (i=1;i<=5;i++) { j++; } i=1; while(i<=5) { j++ ;i++;} i=1; do { j++ ;i++; } while (i<=5);

More Related