C語言學習日記第六篇
阿新 • • 發佈:2021-12-01
1.break;和continue;的區別
1 #include <stdio.h> 2 3 int main(){ 4 5 int ch = 0; 6 7 while ((ch = getchar()) != EOF) 8 9 { 10 11 if (ch<'0' || ch>'9') 12 13 break; //【continue;】//break是終止迴圈,直接結束程序。而continue putchar(ch); 則是終止本次迴圈,還會將值返回判斷是否滿足條件。 14 15 } 16 17 return 0; 18 19 }
2.for
1 #include <stdio.h> 2 3 int main(){ 4 5 int i=1; 6 7 while (i <= 10) 8 9 { 10 11 if (i == 5) 12 13 continue; 14 15 printf("%d", i); 16 17 i++; 18 19 } 20 21 /*for (i = 1; i <= 10; i++){ 22 23 if (i == 5) 24 25 continue; 26 27 printf("%d", i);28 29 }*/ 30 31 return 0; 32 33 }//while的結果是1234 因為while迴圈遇見i=5時,不執行後面的程式碼。然後返回 34 35 //for的結果是1234678910判斷i<=10。依然遇見i==5。for迴圈遇見continue後跳進for (i = 1; i <= 10; i++)。依然要進行i++,i變為6,所以輸出為1234678910。
【兩者()中都是判斷條件== <= >= !=】
3.do...while迴圈
1 #include <stdio.h> 2 3 int main(){ 4 5 inti = 1; 6 7 do 8 9 { 10 11 printf("%d\n", i); 12 13 i++; 14 15 } 16 17 while (i <= 10); 18 19 return 0; 20 21 }