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




GO - CONTINUE


'Continue' statement is used with the loops to skip a few lines of code below it.


Let us make it simple with the below example.


'Continue' with 'for loop'


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, we don't want the number '2' to be printed. We just want to print '1' and '3' as output.


Let us rewrite the program using 'continue' statement.


Example :



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


Output :



 1
 3

Now, if you see the output, '2' is omitted from the output, printing only '1' and '3' as output.


Let us see it in detail :


So, we have a 'for loop' that prints the numbers from 1 to 3.


for i := 1; i <= 3; i++ {
	
	if (i == 2) {
		continue
	}
 		 
	fmt.Println(i)     	
}

And the Iteration starts,


1st Iteration


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


java_Collections

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


if (i == 2) {
	continue
}

In this case the value of 'i' is '1'. So, we do not enter the 'if block' and come to the print statement.


fmt.Println(i)

Printing the value of 'i'.


Output :



 1

Then we start the second Iteration of 'for loop'.


2nd Iteration


In the 2nd Iteration, '2' is taken and stored in the variable 'i'.


java_Collections

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


if (i == 2) {
	continue
}

In this case the value of 'i' is '2'. So, we enter the 'if block' and come to the continue statement.


continue

And what the 'continue' statement does is, ends the current Iteration of the 'for loop' and starts the next Iteration.


java_Collections

And the value of 'i' i.e. '2' is not printed.


And the 3rd Iteration starts.


3rd Iteration


Similarly, in the 3rd Iteration, '3' is taken and stored in the variable 'i'.


java_Collections

Same way, in the next line, we check if the value of the variable 'i' is '2' or not.


if (i == 2) {
	continue
}

In this case the value of 'i' is '3'. So, we do not enter the 'if block' and come to the print statement.


fmt.Println(i)

Printing the value of 'i'.


Output :



 1
 3

With this we end the execution of 'for loop'.