Break statement
We often come across situations where we want to jump out of a loop instantly, without waiting to get back to the conditional test. The keyword break allows us to do this. When break is encountered inside any loop, control automatically passes to the first statement after the loop.
A break is usually associated with an if.
Simple Example :
#include <stdio.h>
#include <conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=7;i++)
{
if(i==3)
break;
printf("\n%d",i);
}
getch();
}
Output :
1
2
Description :
The for loop execute from i=1, since the condition is true hence its value is printed this
is continued for i=2 and again printing its value.But wheni=3 then if condition is true and
the break statement executes terminating the control from the loop.
Another Example:
This example is already explained in the Switch case section.
#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter any number from 1 to 3 :");
scanf("%d",&no);
switch(no)
{
case 1:
printf("\n\n It is 1 !");
break;
case 2:
printf("\n\n It is 2 !");
break;
case 3:
printf("\n\n It is 3 !");
break;
default:
printf("\n\n Invalid number !");
}
getch();
}
Prev NEXT
0 comments:
Post a Comment