Break Statement

The break statement terminates the loop (for,while and do-while) immediately when it is encountered. The break statement is used with decision making statement such as if...esle.

 

The break statement in C programming has the following two usages −

  • break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.

  • It can be used to terminate a case in thWhen e switch statement 

 

Syntax-

break;

 

FLOW DIAGRAM

C break statement

 

Example-

#include <stdio.h>
int main()
{
     int num =0;
     while(num<=100)     {
        printf("value of variable num is: %d", num);
if (num==2)        {   
         break;    
    }     
   num++; 
    }    
 printf("Out of while-loop");  
}
return 0;
}

Output

value of variable num is: 0
value of variable num is: 1
value of variable num is: 2
Out of while-loop

Example-

#include <stdio.h>
int main(){
      int num; 
     printf("Enter value of num:");  
    scanf("%d",&num);      
switch (num)  {  
        case 1:
             printf("You have entered value 1
");  
           break;         
 case 2: 
printf("You have entered value 2
");
  break;
  case 3:
  printf("You have entered value 3
");         
break; 
  default:   printf("Input value is other than 1,2 & 3 "); 
    }     return 0;
}

 

Output

Enter value of num:2
You have entered value 2

You would always want to use break statement in a switch case block, otherwise once a case block is executed, the rest of the subsequent case blocks will execute. For example, if we don’t use the break statement after every case block then the output of this program would be:

 

Enter value of num:2
You have entered value 2
You have entered value 3
Input value is other than 1,2 & 3