break statement

break statement is used to go out from a loop. When break; statement is encountered inside a loop then loop is terminated immediately and program control go to the immediate next statement of loop.
Example:

#include<stdio.h>
int main()
{
     int i=1;
     for(;;i++)
     {
          if(i>4)
              break;
          printf("iteration %d\n",i);
     }
     printf("\n\ outside the loop \n",i);
     return 0;
}

OUTPUT

iteration 1
iteration 2
iteration 3
iteration 4

outside the loop

Explanation:
There is no condition in for loop. So iteration will be continuing infinitely. Inside for loop we used a break; statement under if(i>4). So at fifth iteration value of i will be 5 and i>4 will be true and break; statement will be executed.

NOTE:

Here we used

if(i>4)
break;

instead of

if(i>4)
{
   break;
}

For only one statement it is not necessary to use opening and closing curly braces. Actually all statements inside opening and closing curly braces are tread as single statement. This concept is applicable to for loop, while loop and anything else where opening and closing curly braces are used except function. In function opening curly brace represent starting point of function and closing curly brace represent ending of that function.


Next Previous