break statement

When we writing programming code, 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.
The keyword break, breaks the control only from the while in which it is placed.
Let's understand break with c program example:

/*demonstration of break statement through c program*/
#include<stdio.h>
#include<conio.h>
void main()
{
 int i=5;
 clrscr();
 while(i>=1)
 {
  if(i==2)
  {
   printf("\nIt is equal to two!!");
   break;
  }
  printf("%d\n",i);
  i--;
 }
 getch();
}

Output:
5
4
3
It is equal to two!!

Thus, it is clear that a break statement takes the execution control out of the loop.
In above program, if we omitted break statement then what will be output? The answer is
5
4
3
It is equal to two!!
2
1


because when i's value is 2, condition will be satisfy and executed printf statement, after that compiler goes to next statement i.e. printf("%d",i); because loop do not terminate and it is run till the i value is not less than 1.
See more example of break statement

Comments