Learn goto statement of C programming in best way

goto statement in C

In C and C++ if we want to jump from one statement to another statement we need to use goto statement. It is also known as unconditional jump.

goto statement can be use to create loop and run block of code continuously. Infinite loop can be created using goto statement.

Use goto statement instead of loop statements for iteration will make program little complicated.

goto-statement-in-c-itvoyagers

Syntax 1:

    goto label;

    .

    .

    label:

    .

    .

Syntax 2:

    label:

    .

    .

    goto label;

    .

    .

In above syntax label use to specify the position on which we have to jump to.

goto will make jump to the label specified and start executing statements after label.

First syntax can be use to make simple jump from one line to another.

Second syntax can be use to create loop which will help us to execute block of code continuously, this can be done with the help of if-else statement.

Example 1

#include<stdio.h>

void main()
{
printf("itvoyagers.inn");
goto label_1;
printf("Hello, World!n");
printf("This is goto statement examplen");
label_1:
printf("ITVoyagers");
}

Output:

    itvoyagers.in

    ITVoyagers

In above example goto statement will jump to label_1 and it will skip all the statements between, hence we get above output.

Example 2

#include <stdio.h>

void main()
{
    int x=1;
    label_1:
        printf("%d ITVoyagersn",x);
        x++;
        if(x<=5)
        {
            goto label_1;
        }
        else
        {
            printf("Thank You!!");
        }
}

Output:

    1 ITVoyagers
    2 ITVoyagers
    3 ITVoyagers
    4 ITVoyagers
    5 ITVoyagers
    Thank You!!

In above example we have created loop using goto statement and if-else statement.

We have initialized variable x with value 1, then we have set a label.

Next we have print statement and followed by that we have incremented the value of x by 1.

Next we are checking if x<=5 and if this condition is true then we are taking jump to label_1 with the help of goto statement.

When condition gets invalid then else part will get executed.

CHECKOUT OTHER RELATED TOPICS

CHECKOUT OTHER QUIZZES

PRACTICALS IN C PROGRAM

We are aiming to explain all concepts of C in easiest terms as possible.
ITVoyagers-logo
ITVoyagers
Author

Leave a Comment