break statement in c

  • The keyword break allows the programmers to terminate the loop. The break skips from the loop or block in which it is defined.
  • The control then automatically goes to the first statement after the loop or block. The break can be associated with all conditional statements.
  • We can also use break statements in the nested loops. If we use break statement in the innermost loop, then the control of the program is terminated only from the innermost loop.
  • The break statement causes an immediate exit from a loop. Because the code that follows it in the loop is not executed if the break is reached, you can also sometimes avoid nesting by including a break.
  • It is possible to force an immediate exit from a loop, bypassing the loop’s conditional test, by using the break statement.

Syntax-

break;

Flow Diagram break statement:

    break statement in c

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