This blog is under construction

Saturday, 21 April 2012

break statement

Syntax for break statement:
while (expression) {               
        <statements>;            
         break; 
}

break statement is used to end loop construct or transfer program control to the end of the loop construct where the loop can be either for, while or do while.  Let us try to understand the behavior of break statement using a C program.  Below program would print numbers from 1 to 5.  When the value of variable num is 6, the expression in if statement would evaluate to be true resulting to the execution of break statement which will transfer the program flow to the end of the loop.

Example C program using break statement:
 
  #include <stdio.h>

  int main() {
        int num;
        printf("Print first 5 Natural numbers:\n");
        for (num = 1; num < 10; num++) {
                if (num == 6)
                        break;  // execute break statement if the value of i is 6
                printf("%d\n", num);  // print the value of num
        }
        return 0;
  } 

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Print first 5 Natural numbers:
  1
  2
  3
  4
  5 


break statement inside inner loop:
Execution of break statement in inner loop results to termination or end of inner loop(the loop in which break statement is executed) alone.  Similarly, break in switch statement moves the control to the end of switch statement.  Let us write a simple C program to understand the behavior of break statement inside inner loop.

 
  #include <stdio.h>
  int main() {
        int i = 1, j;
        while (i < 3) {  // outer loop
                printf("Outer loop - value of i is %d\n", i);
                j = 0;
                while (j < 5) {  // inner loop
                        printf("Value of j is %d\n", j);
                        if (j == 3) { // executes break if j is 3
                                printf("j is %d..break inner loop!!\n\n", j);
                                /*
                                 * break in inner loop.  Here, execution
                                 * of break terminates inner loop
                                 */
                                break;
                        }
                        j++;
                }
                i++;
        }
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Outer loop - value of i is 1
  Value of j is 0
  Value of j is 1
  Value of j is 2
  Value of j is 3
  j is 3..break inner loop!!

  Outer loop - value of i is 2
  Value of j is 0
  Value of j is 1
  Value of j is 2
  Value of j is 3
  j is 3..break inner loop!!



No comments:

Post a Comment