[分享]C语言——break和continue跳出循环
#include
int main() {
//while()
char CH;
int count=0;
while(count < 10){
CH = getchar();
if(CH != ' ')
break;
putchar(CH);
count++;
}
printf("Hello, World!\n");
return 0;
}
for循环及嵌套循环示例:注:只会直接跳出内层循环,外层循环正常执行#include
int main() {
char ch;
int cunt;
int i;
for(cunt=0;cunt<10;cunt++){
ch = getchar();
for(i=0;i<5;i++){
if (ch != ' ')
break;
putchar(ch);
printf("我是内层循环的---小可爱!!!\n");
}
printf("我是外层循环的---小可爱!!!\n");
printf("如果continue语句在嵌套循环内,则只会影响包含continue的内层循环,不影响外层循环!!!\n");
}
printf("Hello, World!\n");
return 0;
}
要想外层循环一并终止;需要在外层在使用 break;#include
int main() {
char ch;
int cunt;
int i;
for(cunt=0;cunt<10;cunt++){
ch = getchar();
for(i=0;i<5;i++){
if (ch != ' ')
break;
putchar(ch);
printf("我是内层循环的---小可爱!!!\n");
}
if (ch != ' ')
break;
printf("我是外层循环的---小可爱!!!\n");
printf("如果continue语句在嵌套循环内,则只会影响包含continue的内层循环,不影响外层循环!!!\n");
}
printf("Hello, World!\n");
return 0;
}
在多重选择 switch 语句中使用 continue 和 break的示例:/* animals.c -- uses a switch statement */
#include
#include
int main(void)
{
char ch;
printf("Give me a letter of the alphabet, and I will give ");
printf("an animal name\nbeginning with that letter.\n");
printf("Please type in a letter; type # to end my act.\n");
while ((ch = getchar()) != '#')
{
if('\n' == ch)
continue;
if (islower(ch)) /* lowercase only */
switch (ch)
{
case 'a' :
printf("argali, a wild sheep of Asia\n");
break;
case 'b' :
printf("babirusa, a wild pig of Malay\n");
break;
case 'c' :
printf("coati, racoonlike mammal\n");
break;
case 'd' :
printf("desman, aquatic, molelike critter\n");
break;
case 'e' :
printf("echidna, the spiny anteater\n");
break;
case 'f' :
printf("fisher, brownish marten\n");
break;
default :
printf("That's a stumper!\n");
} /* end of switch */
else
printf("I recognize only lowercase letters.\n");
while (getchar() != '\n')
continue; /* skip rest of input line */
printf("Please type another letter or a #.\n");
} /* while loop end */
printf("Bye!\n");
return 0;
}
在本例中 continue 的作用与上述类似,但是 break 的作用不同:它让程序离开 switch 语句,跳至switch语句后面的下一条语句;如果没有 break 语句,就会从匹配标签开始执行到 switch 末尾;注:C语言中的 case 一般都指定一个值,不能使用一个范围;switch 在圆括号中的测试表达式的值应该是一个整数值(包括 char 类型);case 标签必须是整数类型(包括 char 类型)的常量 或 整型常量表达式( 即, 表达式中只包含整型常量)。不能使用变量作为 case 的标签switch中有 break
微信图片_20210302115720.png (107.22 KB, 下载次数: 400)
下载附件
2021-3-2 11:59 上传
遇到break后跳出,继续匹配switch。switch 中 无break
微信图片_20210302115723.png (110.35 KB, 下载次数: 403)
下载附件
2021-3-2 11:59 上传
顺序执行每个case。