Keyword Break and Continue in C Language
Keyword Break and Continue in C Language
Break keyword
Break keyword is used only in:
In
the body of loop
In
the body of switch
For example we have to make a program to take input a number from user, which should be an even number. We give at the most three chances to the user to input correct value. It is like a game where user has three chances. If user entered an even number the game is in his pocket (win the game) otherwise he loses the game. Suppose user inputs an even number in the first chance, then no more chances are needed as he already wins the game. So we have to use break keyword to terminate the iterations.
int main()
{
int x, i=1;
while(i<3)
{
printf(" enter an even num");
scanf("%d", &x);
if (x%2= = 0)
{
printf("you win");
break;
}
i++;
}
if (i = =4)
printf("you lost");
return (0);
}
{
int x, i=1;
while(i<3)
{
printf(" enter an even num");
scanf("%d", &x);
if (x%2= = 0)
{
printf("you win");
break;
}
i++;
}
if (i = =4)
printf("you lost");
return (0);
}
Continue keyword
The keyword continue is used only
in the body of loop.
It is used to move control at termination condition in the case of while and do-while loop. continue is used in for loop to transfer control at flow part (increment/decrement).
It is used to move control at termination condition in the case of while and do-while loop. continue is used in for loop to transfer control at flow part (increment/decrement).
EXAMPLE
int main()
{
int x;
while(1)
{
printf(“Enter an even number”);
scanf(“%d”,&x);
if(x%2==1)
continue;
else
{
printf(“This is the correct value”);
break;
}
}
return(0);
}
In the above program, condition of while loop is always evaluated as TRUE. Any non-zero number is considered as TRUE and zero is considered as FALSE. The loop only ends at the execution of break. If the user enters an odd number condition x%2==1 becomes TRUE, then continue works. Continue transfers the control at while loop condition.
As long as user enters odd number, continue works every time, but when user enters an even number, break terminates loop.
Comments
Post a Comment