c語言中continue語句


 

c語言中continue語句;執行continue語句后,循環體的剩余部分就會被跳過。

 

例子;

1、原始程序。輸出矩形。

#include <stdio.h>

int main(void) { int i, j, height, width; puts("please input the height and width."); do { printf("height = "); scanf("%d", &height); if (height <= 0) puts("the range of height is > 0 "); printf("width = "); scanf("%d", &width); if (width <= 0) puts("the range of width is > 0 "); } while (height <= 0 || width <= 0); for (i = 1; i <= height; i++) { for (j = 1; j <= width; j++) { putchar('*'); } putchar('\n'); } return 0; }

當height和width都大於0時,程序正常輸出矩形。 

當height <= 0時,此時程序已經滿足do語句重新執行的條件,但是任然執行width的輸入,因此需要改進。以下使用break改進。

 

2、使用break

#include <stdio.h>

int main(void) { int i, j, height, width; puts("please input the height and width."); do { printf("height = "); scanf("%d", &height); if (height <= 0) { puts("the range of height is > 0 "); break; } printf("width = "); scanf("%d", &width); if (width <= 0) puts("the range of width is > 0 "); } while (height <= 0 || width <= 0); for (i = 1; i <= height; i++) { for (j = 1; j <= width; j++) { putchar('*'); } putchar('\n'); } return 0; }

當height和width都大於0時程序正常執行,但是當height小於等於0時,程序就直接退出了。 以下使用continue語句改進。

 

3、使用continue

#include <stdio.h>

int main(void) { int i, j, height, width; puts("please input the height and width."); do { printf("height = "); scanf("%d", &height); if (height <= 0) { puts("the range of height is > 0 "); continue; } printf("width = "); scanf("%d", &width); if (width <= 0) puts("the range of width is > 0"); } while (height <= 0 || width <= 0); for (i = 1; i <= height; i++) { for (j = 1; j <= width; j++) { putchar('*'); } putchar('\n'); } return 0; }

當height小於等於0時,程序會跳過循環體的剩余部分。

執行continue語句后,循環體的剩余部分就會被跳過。

 

例子:

#include <stdio.h>

int main(void) { int i, j; puts("please input an integer."); printf("j = "); scanf("%d", &j); for (i = 1; i <= j; i++) { if (i == 6) break; printf("%d ", i); } putchar('\n'); puts("xxxxxyyyyyy"); return 0; }

 

 break語句會直接終止循環。

 

下面看continue。

#include <stdio.h>

int main(void) { int i, j; puts("please input an integer."); printf("j = "); scanf("%d", &j); for (i = 1; i <= j; i++) { if (i == 6) continue; printf("%d ", i); } putchar('\n'); puts("xxxxxyyyyyy"); return 0; }

 

 continue語句則是僅僅跳出“6”的那一次執行過程。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM