Thursday, 29 May 2014

Break And Continue in C

Break:
The break statement allows you to exit a loop from any point within its body, bypassing its normal termination expression. When the break statement is encountered inside a loop, the loop is immediately terminated, and program control resumes at the next statement following the loop. The break statement can be used with all three of C's loops for, while and do...while loops.
Syntax:
break;

The figure below explains the working of break statement in all three type of loops.


Here's an example of a use for the break statement:
#include
int main()
{
 int t ;
 for ( ; ; ) 
 {
  scanf("Enter any no.\n%d" , &t) ;
  if ( t==10 ) 
                break ;
 }
 printf("End of an infinite loop...\n");
 return 0;
 }
Output:
Enter any no.
2
3
10
End of an infinite loop...
In above example, it takes no. until user enter 10 because t=10 then it will break.

Continue:
The continue statement is somewhat the opposite of the break statement. It forces the next iteration of the loop to take place, skipping any code in between itself and the test condition of the loop. In while and do-while loops, a continue statement will cause control to go directly to the test condition and then continue the looping process. In the case of the for loop, the increment part of the loop continues. One good use of continue is to restart a statement sequence when an error occurs.

Syntax:
continue; 

Here's an example of a use for the break statement:

#include
int main()
{
 int x ;
 for ( x=0 ; x<=100 ; x++) 
 {
  if (x%2) continue;
  printf("%d\n" , x);
 }
}

0 comments :

Post a Comment