This blog is under construction

Saturday, 21 April 2012

continue statement

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

continue statement transfers the control to the beginning of the loop construct.  In other words, it terminates the current iteration(statements below continue won't get executed) and starts next iteration of the loop.

Example C program using continue statement:
 
  #include <stdio.h>
  int main() {
        char ch;
        while ((ch = getchar()) != '\n') {  // start of the loop
                if (ch == 'a')  /* character 'a' alone won't get printed */
                        continue;  // moves control to start of the loop
                printf("%c", ch);
        }
        printf("\n");
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  aaaaa bbbb aaabbb ccaaacc ddaaadddd
   bbbb bbb cccc dddddd
 

Note:
The input characters other than 'a' are printed on the output screen.  Why character 'a' is skipped?  Because, program executes continue statement if the input character is 'a' and the control moves to the start of the loop, skipping statements below continue.

continue inside inner loop:
continue statement inside inner loop transfers the control to the beginning of inner loop. (ie) only inner loop is getting affected in this case.

 
  int main() {
        int i = 0, j;
        while (i < 3) {  // outer loop
                printf("Outer loop- value of i is %d\n", i);
                j = 0;  // initialization
                while (j < 5) {  // inner loop
                        j++;
                        if (j <= 3) {  // execute continue if j <= 3
                                /*
                                 * moves control to the start of
                                 * inner loop.  Statments below
                                 * continue won't be executed
                                 */
                                continue;
                        }
                        printf("Inner loop - value of j is %d\n", j);
                }
                i++;
                printf("\n");
        }
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Outer loop- value of i is 0
  Inner loop - value of j is 4
  Inner loop - value of j is 5

  Outer loop- value of i is 1
  Inner loop - value of j is 4
  Inner loop - value of j is 5

  Outer loop- value of i is 2
  Inner loop - value of j is 4
  Inner loop - value of j is 5



No comments:

Post a Comment