Goto statement in C

Goto Function 

The Goto function is used for transferring the control of the command to a specific label (which is represented by a variable ). The goto function in C mainly has two functions :-  
  1. Repeating a piece of Code.
  2. Skipping a piece of Code.

Syntax of the Goto Function when Skipping a piece of code 

goto label<variable_name>;
..............
..............
..............
label:


Syntax of the Goto Function when Repeating a piece of code 

label:
..............
..............
..............
goto label<variable_name>;

Example 1. ( Repeating by using Goto function )

Find the sum of first n numbers based on the user input,using goto statement

#include <stdio.h>

int main()
{
    int n,condition=1,i=0,sum=0;
    printf(" Enter n = ");
    scanf("%d",&n);
    
    jump:
    sum=sum+i;
    i++;
    
    if(i<=n)
    {
        goto jump;
    }
    printf("\n The sum of n numbers is : %d ",sum);
    return 0;

}

Example 2. ( Skipping by using  Goto function )

 Find the sum of first n numbers based on the user input, using goto statement

#include <stdio.h>

int main()
{
    int n,condition=1,i=0,sum=0;
    printf(" Enter n = ");
    scanf("%d",&n);
    
    while(condition==1)
    {
        sum=sum+i;
        if(i==n)
        {
            goto jump;
        }
        i++;
    }
    jump:
    printf("\n The sum of n numbers is : %d ",sum);
    return 0;
}



Comments

Popular posts from this blog

Bubble Sort ( C & Python 3)

Something about me

Comparison Logical and Bitwise Operator ( Java Part - 4 )