Home C Programming Tutorial Goto Statement in C Programming

Goto Statement in C Programming

by anupmaurya
3 minutes read

The goto statement is another type of control statement supported by C. The control is unconditionally transferred to the statement associated with the label specified in the goto statement.

SYNTAX

goto labelname;
labelname:

A statement label is defined in exactly the same way as a variable name, which is a sequence of letters and digits, the first of which must be a letter. The statement label must be followed by a colon (:). Like other statements, the goto statement ends with a semicolon.

EXAMPLE

Print first N natural numbers in C programming using the goto statement.

 #include<stdio.h>
 int main()
 {
   int n, i=1;

   printf("Enter a number: ");
   scanf("%d",&n);
   
   start:
   printf("%d\t",i);
   i++;
   if(i<n) goto start;
   
   return 0;
 }

Output:-

Enter a number: 10
1 2 3 4 5 6 7 8 9

The operands may be an expression, constants or variables. It starts with a condition, hence it is called a conditional operator.

Use of goto statement

The goto statement is used:-

  1. To execute a group of statements repeatedly for a particular number of times.
  2. To come out of several nested loops at one stroke.

EXAMPLE

Write a program to find factorial of a given number in C programming using the goto statement.

 #include<stdio.h>
 int main()
 {
   int num;
   long fact = 1;
   printf("Enter a number: ");
   scanf("%d",&num);
   
   if(num<0) goto end;
   for(int i=1; i<=num; i++)
   fact = fact * i;
   printf("Factorial of %d is = %ld", num, fact);
   end:
   
   return 0;
 }

OUTPUT

Enter a number: 5
Factorial of 5 is = 120

In the above program for calculating the factorial, we used a goto statement and for loop. We can do the same without using for loop also. The below program is without for loop.

 #include<stdio.h>
 int main()
 {
   int num;
   long fact = 1;
   printf("Enter a number: ");
   scanf("%d",&num);
   
   if(num<0) goto end;
   int i=1;
   loop:
   fact = fact * i;
   i++;
   if(i<=num) goto loop;
   printf("Factorial of %d is = %ld", num, fact);
   end:
   
   return 0;
 }

OUTPUT

Enter a number: 5
Factorial of 5 is = 120
Enter a number: 6
Factorial of 6 is = 720
Enter a number: 7
Factorial of 7 is = 5040

Note:- Generally, we don’t use the goto statement in C programming. It is recommended to use loops instead of using goto statement. Use goto statement, only if loops can’t do that operation.

Because the goto statement can interfere with the normal sequence of processing, it makes a program more difficult to read and maintain.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.