ITDeveloper : C Programming
C Programming
Step by Step Tutorials
![]() Share with a Friend |
goto statement in C
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 = 50;
int i, num, sum;
double average;
sum=0;
for (i = 1; i <= maxInput; ++i) {
printf("%d. Enter a number: ", i);
scanf("%d", &num);
// go to jump if the user enters a negative number
if (num < 0) {
goto jump;
}
sum += num;
}
jump:
average = sum / (i - 1);
printf("Sum = %d\n", sum);
printf("Average = %.2f", average);
return 0;
}
OUTPUT:
- Enter a number: 5
- Enter a number: 10
- Enter a number: 15
- Enter a number: 20
- Enter a number: 25
- Enter a number: -1
Sum = 75
Average = 15.00