The keyword break

The keyword break is used only in:

  • In the body of loop
  • In the body of switch







The keyword break is used in the body of loop to terminate execution of loop before completion of normal life of the loop. Sometimes it is desired to terminate loop before its last iteration.
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 number”); scanf(“%d”,&x); if(x%2==0) { printf(“You Win”); break; } i++; } if(i==4) printf(“You lost”); return(0); }

Keyword break
Tagged on: