Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




GO - GOTO


'Goto' statement is used to skip a few lines of code below it.


We can make the best use of as a loop.


Let us make it simple with the below example.


Say we have a 'for loop' that prints the numbers from 1, 2 and 3.


Example :



package main
import "fmt"
	
func main() {
		
	for i := 1; i <= 3; i++ {
		fmt.Println(i)
	}
}


Output :



 1
 2
 3

Now, let's say, want to get the same output


And this time we won't be using any kind of loops. Just use 'goto' and make it work as a loop.


Let us rewrite the program using 'goto' statement.


Example :



package main
import "fmt"
	
func main() {
		
	i := 1
		
	MyLoop :
	fmt.Println(i)
	if (i < 3) {
		i++
		goto MyLoop
	}
}


Output :



 1
 2
 3

Now, if you see the output, the numbers 1, 2 and 3 are printed.


Let us see it in detail :


Initially we have created a variable called 'i' and assigned it with '1'.


i := 1

java_Collections

So, we have something called as level, i.e. 'MyLoop' followed by colon ':'.


MyLoop :

And the so called 'loop' with 'goto' happens in the next few lines.


MyLoop :
fmt.Println(i)
if (i < 3) {
	i++
	goto MyLoop
}

And the Iteration starts,


1st Iteration


In the 1st Iteration, '1' is already stored in the variable 'i'.


java_Collections

In the next line, we have the print statement.


fmt.Println(i)

Printing the value of 'i'.


Output :



 1

So, in the next line, we check if the value of the variable 'i' is less than '3' or not.


if (i < 3) {
	i++
	goto MyLoop
}

What happens is the value of 'i' gets incremented by 1 and becomes 2.


java_Collections

Then we come to the 'goto' statement. Which asks the loop to goto the Level 'MyLoop'.


java_Collections

Then we start the second Iteration.


2nd Iteration


In the 2nd Iteration, the value of 'i' is '2'.


java_Collections

In the next line, we have the print statement.


fmt.Println(i)

Printing the value of 'i'.


Output :



 1
 2

And the 3rd Iteration starts.


And in the same way the values are printed using 'goto'.