The
goto
statement allows us to transfer control of the program to the specified label.Syntax of goto Statement
goto label;
... .. ...
... .. ...
label:
statement;
The label is an identifier. When the
goto
statement is encountered, the control of the program jumps to label:
and starts executing the code.
Example: goto Statement
// Program to calculate the sum and average of positive numbers
// If the user enters a negative number, the sum and average are displayed.
# include <stdio.h>
int main()
{
const int maxInput = 5;
int i;
double number, average, sum=0.0;
for(i=1; i<=maxInput; ++i)
{
printf("%d. Enter a number: ", i);
scanf("%lf",&number);
if(number < 0.0)
goto jump;
sum += number;
}
jump:
average=sum/(i-1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}
Output
1. Enter a number: 3 2. Enter a number: 4.3 3. Enter a number: 9.3 4. Enter a number: -2.9 Sum = 16.60
0 Comments