Looping in Golang


January 13, 2022, Learn eTutorial
1189

In this tutorial, you will learn about another control flow structure that is available in the Go programming language known as looping. In the previous tutorial, you learned two ways of introducing branching logic like decision-making statements with if, if-else, if-else if, etc., and switch statements. We will learn for loop and for range loop their syntax usage in the Go program.

For loop statements in Golang

For loop, statements allow execution of a collection of statements multiple times. For loop, the statement is broken down into three different parts. Further, these three parts can form various syntax for successful loop iteration. 

Generally in Golang looping can be of two types 

  •   for loop
  •   for range loop

You will understand what is a simple loop, how to exit a loop & how to loop through collections.

Simple loops in Golang

Let us understand the basics of for loop before getting started with a loop in Go language. The for keyword is followed by three statements

  •   The first statement is an initializer. This statement is executed first before the first iteration.
  •   The second statement is any comparison operation for checking condition which generates a Boolean result.
  •   The last/third statement is the incrementor. Usually used to increment a counter variable.
     

Syntax of basic for loop:-


for    initializer; condition;   incrementor {
}

GO : For Loop

Simple for loop program


package main
import ("fmt")

func main() {
  for i:=0; i<=6; i++ {
    fmt.Println(i)
  }
}

Output:


0
1
2
3
4
5
6

Explanation:

The initialization part initializes a variable i with the value 0. The condition part is i<=6, up to the value of i is less than 6 we need to print the value corresponding to i. The below table briefs how iteration and condition are checked during each iteration. When the value of I becomes 7 the condition becomes false and finally exits the loop. During each iteration print the output, which displays the current value of i as shown in the output.

GO : For-loop

How to increment two variables in Golang

Golang allows multiple variable incrementations in for loop as in other languages but you need to know the syntax to code multiple variable initialization and incrementation inside for loops.
The syntax for multiple variable incrementation and initialization:


  for i , j :=0 , 0 ;   I <= 6;    i, j = i+1, j+1 {
}

Let's understand with an example


package main
import ("fmt")

func main() {
  for i , j :=0,0 ;i<=6; i,j = i+1,j+1 {
    fmt.Println(i,j)
  }
}

Output:


0 0
1 1
2 2
3 3
4 4
5 5
6 6

For loop with only condition & incrementor

In the above programs, we discussed general for loop syntax. In Golang a for loop can be declared in another format or syntax . There is no need of giving all three statements in a for loop. The value of i in our example or any variable to be initialized can be initialized out of for loop. So the first statement becomes empty in for loop but the semicolon “; “ should be placed in properly otherwise will result in a compiler error.

Syntax:-


Initialize
for      ;  condition ; increment

Let us understand with a program


package main
import "fmt"

func main() {
    i := 0           //initializing i
    for ; i < 5; i++ { //for loop with condition part & incrementor
        fmt.Println(i)
       
    }

Output:


0
1
2
3
4

While loops in Golang / For loop with the only condition

Another type of for loop syntax in Golang which simple as the above syntax.
Syntax :


Initialize
for condition {
}
incrementor

Let us understand with an example


package main
import "fmt"

func main() {
    i := 0
    for i < 6 {
        fmt.Println(i)
        i++
    }
}

Output:


0
1
2
3
4
5

Break Statement in for loop in Golang

A break statement exits out of for loop in a Go language. The codes just after the break statements are not executed afterward.

Syntax: A keyword break.


package main

import (
    "fmt"
)

func main() {
    i := 0
    for {
        fmt.Println(i)
        i++
        if i >= 4 {
            break
        }
    }
}

Output:


0
1
2
3

for loop with only condition, the syntax is used in the above program. The condition is given inside an if statement is when the value of i exceeds 3 stop execution is mentioned by a break statement. Here the break statement exit from for loop when the above-mentioned condition is satisfied.

Continue Statement in for loop in Golang

The continue statement omits the specified iteration of for loop and moves to the next iteration just after it.

Syntax: A keyword continue

Program with continue statement


package main
import ("fmt")

func main() {
  for i:=0; i < 8; i++ {    //for  loop
    if i == 6 {
      continue            //continue statement
    }
   fmt.Println(i)
  }
}

Output:


0
1
2
3
4
5
7

The above-given program skips the 6th iteration and moves forward to the next iteration in the for loop to print the value of i.

Nested for loop

A nested loop is consisting of one inner loop and one outer loop i.e. a for loop with another for loop inside it.

Syntax:


For loop outer {
       For loop inner {
            }
}

Program to understand Nested for loop


package main
import ("fmt")

func main() {
language := [2]string{"Go", "Python"}
tutorials := [3]string{"learn eTutotials", "site1", "site2"}
for i:=0; i < len( language); i++ {
for j:=0; j < len( tutorials); j++ {
fmt.Printf("i= %d j=%d\n", i, j)
fmt.Println( language[i], tutorials[j])
}
}
}

Output:


i= 0 j=0
Go learn eTutotials
i= 0 j=1
Go site1
i= 0 j=2
Go site2
i= 1 j=0
Python learn eTutotials
i= 1 j=1
Python site1
i= 1 j=2
Python site2

Explanation

In the above example two arrays are created, language and tutorials of string data type. The outer for loop consists of three statements. The lens (language) function contains the length of language ie 2 and the length of tutorials is 3 .we have discussed len () function in arrays


for    initializer; condition;   incrementor {
}

for i:=0; i <2; i++ { // outer loop



   for j:=0; j < 3; j++ { //inner loop

      fmt.Println( language[i], tutorials[j])

  }

}

For the first outer loop iteration when i=0, the inner loop iterates and prints Go learn etutorials.Here language [0] is Go & tutorial [0] is learn eTutotials.So prints Go learn eTutotials.Here inner loop continues iteration till it exits out of the loop. For example, again j is incremented j becomes 1, the condition is checked 1 < 3, increments j and print language [0] tutorials [1] so the output will be Go site1 and continues till exit out of the inner loop for first outer iteration.
Next time outer loop increments and carry out the same above steps to print the rest of the portions shown in the output.

For – Range loop in Golang

For range loop in Golang is used to iterate over a different collection of data structures such as arrays, maps, etc. The range keyword iterates over an array, map or slice.

Syntax


for index, value := range map/slice/array {
//Code to execute
} 

Program to understand for range concept


package main
import ("fmt")

func main() {
  s := [ ]int{1,2,3}
  for index,value := range s {   // for range loop
     fmt.Printf("%v\t%v\n", index, value)
  }
}

Output:


0 1
1 2
2 3

Explanation :

The above-given code works with a slice. The syntax starts with for keyword to iterate over slice s starting from index 0. The range keyword iterates over each slice element and stores the corresponding value in value.
For example, when the index is 0, the range keyword iterates over the first slice element here it is 1. So the value 1 is stored in a variable declared as a value for assigning/storing the slice element. The same procedure repeats till reaches the end of the index i.e. here last is 2. The output shown above makes the concept clear.