break


break

            An early exit from the loops will be accomplished using break or goto statements. It is generally used to come out from a loop or to exit from a switch. This statement can be used within for, while ,do-while, switch. In an iterative statement, the break statement ends the loop and moves control to the next statement outside the loop. Within nested statements, the break statement ends only the smallest enclosing do, for, switch, or while statement.In a switch statement, the break passes control out of the switch body to the next statement outside the switch statement.
            When a break statement is encountered inside a loop, the loop will be terminated immediately and the program continues with the statements immediately following the loop. But when loops are nested, the break only exit from the loop containing it i.e. the break will exit a single loop.

Syntax:-
break;

Sample program to illustrate the break statement in single loop.

#include<stdio.h>
#include<conio.h>
void main()
{
 int i;
 clrscr();
 for(i=1;i<=10;i++)
 {
  printf("%d",i);
  if(i==4)
   break;
  printf("hello \n");
 }
 printf("Out of loop..");
 getch();
}

Output

1hello
2hello
3hello
4Out of loop..

Sample program to illustrate the break statement with in nested loops.

#include<stdio.h>
#include<conio.h>
void main()
{
 int i,j;
 clrscr();
 for(i=1;i<=4;i++)
 {
  for(j=1;j<=4;j++)
  {
   printf("i,j=%d,%d  ",i,j);
    if(j==2)
   break;
  }
  printf("Out of inner loop..");
  printf("\n");
 }
}
Output

i,j=1,1  i,j=1,2  Out of inner loop..
i,j=2,1  i,j=2,2  Out of inner loop..
i,j=3,1  i,j=3,2  Out of inner loop..
i,j=4,1  i,j=4,2  Out of inner loop..

No comments:

Post a Comment