C break statement

C break statement

Break statement used inside in any loop or switch statements. Sometimes it is necessary to go outside from the loop even before the loop condition becomes false. in such conditions when terminates the loop break statement is used. This break statement cause an immediate exit from the loop in which break statement appear. example it is written as

break;

break statement in c diagram

The break statement in C programming can be used in the following two scenarios:

1. With switch case
2. With loop

when break statement is encounter control is transfer immediately out from the loop. If break written a nested loop structure then it causes exit from the innermost loop.

Let take Example to understand the break statement uses

/* program to understand the use of break*/
#include<stdio.h>
int main()
{
int i;
for(i=0;i<=10;i++)
{
if(i==5)
break;
printf("\n i=%d",i);
}
return 0;
}

in this example its normally executes 11 (0 to 10) times but here the value of i becomes 5 break is encounter and loop is terminated. .

Output

i=0
i=1
i=2
i=3
i=4

C break statement with the nested loop

/* program to understand the use of break with Nested loop */
#include<stdio.h>
int main()
{
int i=1,j=1;//initializing the local variable
for(i=1;i<=4;i++) // outer loop
{
for(j=1;j<=4;j++) // inner loop
{
printf("%d %d\n",i,j);
if(i==3 && j==3)
{
break; //will break loop of j only
}
}
}//end of for loop
return 0;
}

Output

1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4
3 1
3 2
3 3
4 1
4 2
4 3
4 4