C语言break语句
break是C中的关键字,用于使程序控制脱离循环。 break语句在循环或switch语句内使用。 break语句逐个破坏循环,即在嵌套循环的情况下,它首先破坏内部循环,然后再进入外部循环。 C中的break语句可以在以下两种情况下使用:
switch case
With循环
语法:
//loop or switch case
break;
c中中断的流程图
示例
#include<stdio.h>
#include<stdlib.h>
void main ()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);
}
输出
0 1 2 3 4 5 came outside of loop i = 5
带有switch情况的C中断语句示例
单击此处查看使用switch语句的C中断示例。
带有嵌套循环的C break语句
在这种情况下,它仅破坏内部循环,而不破坏外部循环。
#include<stdio.h>
int main(){
int i=1,j=1;//initializing a local variable
for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
printf("%d &d\n",i,j);
if(i==2 && j==2){
break;//will break loop of j only
}
}//end of for loop
return 0;
}
输出
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
正如您在控制台上看到的那样,由于打印i == 2和j == 2后有一个break语句,因此未打印2 3、但是会打印3 1、3 2和3 3,因为break语句仅用于中断内部循环。
带有while循环的break语句
考虑一下以下示例在while循环中使用break语句。
#include<stdio.h>
void main ()
{
int i = 0;
while(1)
{
printf("%d ",i);
i++;
if(i == 10)
break;
}
printf("came out of while loop");
}
输出
0 1 2 3 4 5 6 7 8 9 came out of while loop
带有do-while循环的break语句
请考虑以下示例,将break语句与do-while循环一起使用。
#include<stdio.h>
void main ()
{
int n=2,i,choice;
do
{
i=1;
while(i<=10)
{
printf("%d X %d = %d\n",n,i,n*i);
i++;
}
printf("do you want to continue with the table of %d , enter any non-zero value to continue.",n+1);
scanf("%d",&choice);
if(choice == 0)
{
break;
}
n++;
}while(1);
}
输出
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
do you want to continue with the table of 3 , enter any non-zero value to continue.1
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
do you want to continue with the table of 4 , enter any non-zero value to continue.0