goto control instruction in C

gotoStatement in C language. goto is a jumping statement in c language, which transfer the program's control from one statement to another statement (where label is defined). goto can transfer the program's within the same block and there must a label, where you want to transfer program's control.
goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement in the same function.
NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten to avoid them.

Syntax

The syntax for a goto statement in C is as follows −
goto label;
..
.
label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C program above or below to goto statement.

Flow Diagram

C goto statement

Example:
  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

No comments:

Post a Comment

Featured Post

Core and Advance Python

                      Language Fundamentals