Monday, 21 May 2018

Break statement on nested loop

Break statement on nested loop

  • When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
  • If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.

Program:

/* Break statement on nested loop */
#include <stdio.h>


int main()
{
    int count_1 = 0, count_2 = 0;

    while(1) {

        printf("Vel 1st while count = %d \n", count_1++);
        while(1) {
            printf("Vel Inside 2nd while count %d, 1st while = %d \n",count_2++, count_1);
            sleep(1);
            if(!(count_2 % 5)) {
                /* This break will be apply to this while loop only,
                   1st while loop still be live. */
                break;
            }
        }
        sleep(1);
    }

    return 0;
}

Output:

   sample$ ./a.out
   Vel 1st while count = 0
   Vel Inside 2nd while count 0, 1st while = 1
   Vel Inside 2nd while count 1, 1st while = 1
   Vel Inside 2nd while count 2, 1st while = 1
   Vel Inside 2nd while count 3, 1st while = 1
   Vel Inside 2nd while count 4, 1st while = 1
   Vel 1st while count = 1
   Vel Inside 2nd while count 5, 1st while = 2
   Vel Inside 2nd while count 6, 1st while = 2
   Vel Inside 2nd while count 7, 1st while = 2
   Vel Inside 2nd while count 8, 1st while = 2
   Vel Inside 2nd while count 9, 1st while = 2
   Vel 1st while count = 2
   Vel Inside 2nd while count 10, 1st while = 3
   Vel Inside 2nd while count 11, 1st while = 3
   Vel Inside 2nd while count 12, 1st while = 3
   Vel Inside 2nd while count 13, 1st while = 3
   Vel Inside 2nd while count 14, 1st while = 3
   Vel 1st while count = 3
   Vel Inside 2nd while count 15, 1st while = 4
   Vel Inside 2nd while count 16, 1st while = 4
   Vel Inside 2nd while count 17, 1st while = 4
   Vel Inside 2nd while count 18, 1st while = 4
   Vel Inside 2nd while count 19, 1st while = 4
   Vel 1st while count = 4
   Vel Inside 2nd while count 20, 1st while = 5
   Vel Inside 2nd while count 21, 1st while = 5
   Vel Inside 2nd while count 22, 1st while = 5

No comments:

Post a Comment