C - Jumping Statements

Jumping statements are generally used within a branching statement. Jumping statements are used to jumping out from any loop within its execution.

Types of Jumping Statements are:

Break Statement

Break statement is used to break the execution of the loop. In another words, break statement is use to terminate a loop(while, do while and for) and switch case only. In case of Nested loops, it terminates the control of inner loop only.

Example 1: Program to explain the use of Break statement.

void main()
{
    int i;
    clrscr();
    for(i=1;i<=10;i++)
    {
        if(i==5)
            break; //move the controller, outside loop (line #11)
        printf("%d ",i);
    }
    printf("\nEnd of the program");
    getch();
}
1 2 3 4
End of the program

Example 2: Use of Break statement in Nested Loop.

void main()
{
    int i;
    clrscr();
    for(i=1;i<=5;i++)   //outer loop
    {
        for(j=1;j<=5;j++)   //inner loop
        {	
            if(j==2)
                break; //break inner loop, send controller to outer loop
            printf("%d ",i);
        }
    }
    getch();
}
1 2 3 4 5

Continue Statement

Continue is used to skip the statements. If we don't want to write any statement inside a condition then we can use continue statement.

In other words: continue statement takes the control to the beginning of the loop.

Example 3: Program to explain the use of Continue statement.

void main()
{
    int i;
    clrscr();
    for(i=1;i<=10;i++)
    {
        if(i==5)
            continue; //send the controller to loop, line #5
        printf("%d ", i);
    }
    printf("\nEnd of the program");
    getch();
}
1 2 3 4 6 7 8 9 10
End of the program

Goto Statement

The goto statement can be use anywhere unconditionally in between the program. The goto statement is use to jump the control anywhere in between the program. The word followed by goto keyword is known as label.

Example 4: Program to explain the use of Goto statement.

void main()
{
    printf("1st line");
    goto end; //send the controller to label end
    printf("2nd line");
    printf("3rd line");
    end:
}
1st line

Example 5: Program to explain the use of Goto statement.

void main()
{
    int i;
    clrscr();
    for(i=1;i<=10;i++)
    {
        printf("%d ", i);
        if(i==5)
            goto end;
    }
    end:
    printf("\nEnd of the program");
    getch();
}
1 2 3 4 5
End of the program

Example 6: Print counting 1 to 10 using goto function, without using any loop.

void main()
{
    int counter=1;
    clrscr();
    START:
        printf("%d",counter);
        counter++;
        if(counter<=10)
            goto START;
    getch();
}
1 2 3 4 5 6 7 8 9 10

How to use Break, Continue, Goto Statement