break, continue, goto - Devbhoomi

FREE JOB ALERT & ONLINE TUTORIALS

Hot

Post Top Ad

Sunday 5 November 2017

break, continue, goto

break keyword
break statement neglect the statement after it and exit compound statement. in the loop and transfer the control outside the loop
Break it's sole purpose to passes control out of the compound statement i.e. Loop, Condition, Method or Procedures.
Example :

    while(a)
    {
    while(b)
    {
    if(b == 10)
    {
    break;
    }
    }
    // break will bring us here.
    }

continue keyword
Similar,To break statement continue statement also neglect the statement after it in the loop and send control back to starting point of loop for next iteration instead of outside the loop.
Example :

    #include <stdio.h>
    int main ()
    {
    int a = 10;
    while(a < 20)
    {
    if( a == 15)
    {
    // skip the iteration
    a = a + 1;
    continue;
    }

    printf("value of a: %d\n", a);
    a++;
    }
    return 0;
    }

Output :
 value of a: 10
 value of a: 11
 value of a: 12
 value of a: 13
 value of a: 14
 value of a: 16
 value of a: 17
 value of a: 18
 value of a: 19
goto
  • goto statement transfer the control to the label specified with the goto statement
  • label is any name give to particular part in program
  • label is followed with a colon (:)
Syntax :

    label1:
    -
    -
    goto label1;

Example :

    #include <stdio.h>
    int main()
    {
    int i, j;

    for ( i = 0; i < 10; i++ )
    {
    printf( "Outer loop executing. i = %d\n", i );
    for ( j = 0; j < 3; j++ )
    {
    printf(" Inner loop executing. j = %d\n", j );
    if ( i == 5 )
    {
    goto stop;
    }
    }
    }

    // This message does not print.
    printf( "Loop exited. i = %d\n", i );

    stop:
    printf( "Jumped to stop. i = %d\n", i );
    }

Output :
    Outer loop executing. i = 0
     Inner loop executing. j = 0
     Inner loop executing. j = 1
     Inner loop executing. j = 2
    Outer loop executing. i = 1
     Inner loop executing. j = 0
     Inner loop executing. j = 1
     Inner loop executing. j = 2
    Outer loop executing. i = 2
     Inner loop executing. j = 0
     Inner loop executing. j = 1
     Inner loop executing. j = 2
    Outer loop executing. i = 3
     Inner loop executing. j = 0
     Inner loop executing. j = 1
     Inner loop executing. j = 2
    Outer loop executing. i = 4
     Inner loop executing. j = 0
     Inner loop executing. j = 1
     Inner loop executing. j = 2
    Outer loop executing. i = 5
     Inner loop executing. j = 0
    Jumped to stop. i = 5

No comments:

Post a Comment

Post Top Ad