Break Statement in C
break in c, is a jump statement, allows to exit loop or switch when specific condition is satisfied.
In loops, it is used with if else condition, when any specific condition satisfies, it breaks the loop cycle and comes out of the loop.
In switch, every case ends with break keyword, if any case is matched with switch expression, break transfer the control out of switch statement.
break with for loop
for(int i = 0; i < 5; i++)
{
if(i == 3){
break;
}
}
break with for while loop
int i = 0;
while(i < 5)
{
if(i == 3)
{
break;
}
i++;
}
break with for do while loop
int i = 0;
do{
if(i == 3){
break;
}
i++;
}while(i < 5);
Explanation
In above all loops, when the value of i becomes 3, if condition becomes true and then break will execute and it transfer the execution control out of loop.
break with switch
#include<stdio.h>
void main()
{
int day = 1;
switch(day)
{
case 1:
printf("Monday");
break;
case 1:
printf("Tuesday");
break;
case 1:
printf("Wednesday");
break;
}
}
In switch value of variable day is matched with available cases, then the matched case will execute and break will transfer the control out of switch. In switch break always comes at the end of case.