Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to leave the loop as soon as certain condition becomes true. This is known as jumping out of loop.
The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops. The break statement in C can be used in the following two scenarios:
- with switch case
- with loop
When a break statement is encountered inside the switch case statement, the execution control moves out of the switch statement directly.
Example
#include<stdio.h>
#include<conio.h>
void main(){
int x, y;
printf("Enter the value of X:");
scanf("%d",&x);
printf("Enter the value of Y:");
scanf("%d",&y);
switch(x>y && x+y>0)
{
case 1:
printf("C is a structured programming language.");
break;
case 0:
printf("C is a machine independent language.");
break;
default:
printf("C can easily adopt new features ");
}
getch() ;
}
Output
When the break statement is encountered inside the looping statement, the execution control moves out of the looping statements.
Syntax
for(initialization; test condition ; increment/decrement)
{
............
break;
...........
}
while(condition)
{
........
break;
........
}
do
{
..........
break;
..........
}while(condition);
Example
#include <stdio.h>
#include <conio.h>
int main()
{
int i;
for(i = 0; i<10; i++)
{
printf("\t %d ",i);
if(i == 5)
break;
}
printf("\n came outside of loop i = %d",i);
return 0;
getch();
}
Output
No comments:
Post a Comment