What is a goto statement in c

The goto statement allows us to transfer control of the program to the specified label.

Syntax of goto Statement

  1. goto label;
  2. ... .. ...
  3. ... .. ...
  4. label:
  5. 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.
How goto statement works?

Example: goto Statement

  1. // Program to calculate the sum and average of positive numbers
  2. // If the user enters a negative number, the sum and average are displayed.
  3. # include <stdio.h>
  4. int main()
  5. {
  6. const int maxInput = 5;
  7. int i;
  8. double number, average, sum=0.0;
  9. for(i=1; i<=maxInput; ++i)
  10. {
  11. printf("%d. Enter a number: ", i);
  12. scanf("%lf",&number);
  13. if(number < 0.0)
  14. goto jump;
  15. sum += number;
  16. }
  17. jump:
  18. average=sum/(i-1);
  19. printf("Sum = %.2f\n", sum);
  20. printf("Average = %.2f", average);
  21. return 0;
  22. }
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

Post a Comment

0 Comments