The break
statement can only appear in a switch body or a loop body. It causes the execution of the current enclosing switch or loop body to terminate. A break
may be used to terminate the execution of a switch
, while
, do-while
, or for
.
//loop or switch case break;
#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); }
Click here to see the example of C break with the switch statement.
In such case, it breaks only the inner loop, but not outer loop.
#includeint 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; }
Output
As you can see the output on the console, 2 3 is not printed because there is a break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 are printed because the break statement is used to break the inner loop only.
Consider the following example to use break statement inside while loop.
#include<stdio.h> void main () { int i = 0; while(1) { printf("%d ",i); i++; if(i == 10) break; } printf("came out of while loop"); }
Output
Consider the following example to use the break statement with a do-while loop.
#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); }
A break will only branch out of an inner-most enclosing block, and transfers program-flow to the first statement following the block. For example, consider a nested while-loop.
while (expression) { while (expression) { if (expression) break; statements } statements }
Here the break will terminate the inner while-loop and proceed to execute the statements of the outer while-loop.
This next example shows a fast technique for finding the smallest element in an array of length SIZE. A break is used to terminate the infinite outer while-loop.
i = SIZE; temp = smallest = array[0]; while (1) { while (array[--i] > smallest) ; if (i == 0) break; array[0] = smallest = array[i]; } array[0] = temp;