Skip to main content

example of goto statement in c

/*
C goto statement
The goto statement is known as jump statement in C.
As the name suggests, goto is used to transfer 
the program control to a predefined label. 
The goto statement can be used to repeat some
part of the code for a particular condition.
It can also be used to break the multiple 
loops which can't be done by using a single
break statement. However, using goto is 
avoided these days since it makes the 
program less readable and complicated.
*/
//simple example to use goto statement in C language.

#include <stdio.h>  
int main()   
{  
  int num,i=1;   
  printf("Enter the number whose table you want to multiplication of:-\n");   
  scanf("%d",&num);  
  table:   
  printf("%d x %d = %d\n",num,i,num*i);  
  i++;  
  if(i<=10)  
  goto table;    
}  

//When should we use goto?
/*The only condition in which using goto is preferable is 
when we need to break the multiple loops using a single 
statement at the same time.

Consider the following example.*/
#include <stdio.h>  
int main()   
{  
  int ijk;    
  for(i=0;i<10;i++)  
  {  
    for(j=0;j<5;j++)  
    {  
      for(k=0;k<3;k++)  
      {  
        printf("%d %d %d\n",i,j,k);  
        if(j == 3)  
        {  
          goto out;   
        }  
      }  
    }  
  }  
  out:   
  printf("came out of the loop");   
another example 
#include <stdio.h> int main() { int i,j,k; for(i=0;i<8;i++){ printf("%d",i); for(j=0;j<10;j++){ printf("enter 0 to exit\n"); scanf("%d",&k); if(k==0){ goto end; } } } end: return 0; }

Comments