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 :-
- Repeating a piece of Code.
- Skipping a piece of Code.
Syntax of the Goto Function when Skipping a piece of code
goto label<variable_name>;
..............
..............
..............
label:
label:
Syntax of the Goto Function when Repeating a piece of code
label:
..............
..............
..............
goto label<variable_name>;
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;
}
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
Post a Comment