C – break statement in C programming


C – break statement in C programming



The break statement is used inside loops and switch case.

C – break statement

1. It is used to come out of the loop instantly. When a break statement is encountered inside a loop, the control directly comes out of loop and the loop gets terminated. It is used with if statement, whenever used inside loop.
2. This can also be used in switch case control structure. Whenever it is encountered in switch-case block, the control comes out of the switch-case(see the example below).

Flow diagram of break statement

Syntax:
break;

Example – Use of break in a while loop

#include <stdio.h>
int main()
{
int num =0;
while(num<=100)
{
printf
("value of variable num is: %d\n", 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 – Use of break in a for loop

#include <stdio.h>
int main()
{
int var;
for (var =100; var>=10; var --)
{
printf
("var: %d\n", var);
if (var==99)
{
break;
}
}
printf
("Out of for-loop");
return 0;
}
Output:
var: 100
var: 99
Out of for-loop

Example – Use of break statement in switch-case

#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\n");
break;
case 2:
printf
("You have entered value 2\n");
break;
case 3:
printf
("You have entered value 3\n");
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

Post a Comment

Previous Post Next Post