THE GOTO STATEMENT in C Programming



THE  GOTO STATEMENT:
        The goto statement is used to transfer the control in a program from one point to another point unconditionally. This is also called unconditional branching.

The syntax of the goto statement is:
goto label;
       Where label is a valid identfier used in programming languague ‘C’ to indicate the destination where a control can be transferred. The syntax of label is:
label:
      The various ‘case’ statements in a switch construct also serve as labels used to transfer execution control.







      The goto statement can be used in a program in two ways. These are:

  • Conditional Goto 
  • Unconditional Goto

Conditional Goto:
     The conditional goto statement is used to transfer the control of execution from one part of the program to another part of the program unde a given condition.
For example:
#include<stdio.h>
main()   {
int a, b;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
if(a > b)
goto output1;
else
goto output2;
output1:
printf("Larger value %d\n", a);
goto end;
output2:
printf("Larger value %d\n", b);
end: ;    }
Output:








Uncontitional Goto:
       Unconditional goto statement to used to transfer the  control from one part of the program to the other part without any condition. Normally, a good programmer does not like to use the unconditional goto statements in a program because it may lead to infinite looping as seen in the following program segment.
main()  {
200:
printf(“Unconditional goto \n);
goto 200;    }

Goto statement used in a for loop:
#include<stdio.h>
main()  {
int i, value;
for(i=0; i <= 10; i++)   {
printf("Enter a number: ");
scanf("%d", &value);
if (value <=0)  {
printf("Error\n");
printf("Zero or negative value found\n");
goto error;  }}
error:
return 0;   }
Output:









Goto statement used within a do-while loop:
#include<stdio.h>
main()  {
int i=0, value;
do  {
printf("Enter any number:");
scanf("%d", &value);
if (value <= 0)  {
printf("Error:");
printf("\nZero or negative value found\n");
goto error;  }
i++; }
while(i <= 10);
error:
return 0; }
Output:

THE GOTO STATEMENT in C Programming THE  GOTO STATEMENT in C Programming Reviewed by vijay pratap singh on September 27, 2017 Rating: 5

No comments:

Powered by Blogger.