DEV Community

nadirbasalamah
nadirbasalamah

Posted on • Updated on

Golang tutorial - 4 Control Flow (Iteration)

When creating a software or program, usually there are repetitive instructions or code to complete certain tasks. This repetitive or iterative instruction is called iteration or loop.

Iteration in Go

In Golang, there is only one type of iteration called for loop. The for loop can be customizable based on needs. The anatomy of for loop syntax in Go is like this :
for (init condition; condition; post condition) { ... }
There is for range loop that is suitable for iterating data in an array or slice.
for index, value := range variable {...}

Iteration with for loop

The example of for loop usage can be seen in the code below. This code prints out the number from 1 to 10.

package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        fmt.Println(i)
    }
}
Enter fullscreen mode Exit fullscreen mode

The output:

1
2
3
4
5
6
7
8
9
10
Enter fullscreen mode Exit fullscreen mode

Based on the code example above, the for loop consists of

  • Initiation condition: i := 1 means start execution inside for loop from i equals 1
  • Condition: i <= 10 means if i less than or equals 10, execute the post condition
  • Post condition: i++ means increase or add i value by 1.
  • The code inside for loop which is fmt.Println(i) means print the value of i variable.

The for loop can be customized that give the same result, the customization of the for loop could be like this:

package main

import "fmt"

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

}
Enter fullscreen mode Exit fullscreen mode

The output:

1
2
3
4
5
6
7
8
9
10
Enter fullscreen mode Exit fullscreen mode

Notice in the code example above, that there is a break keyword. The break keyword means to stop or break the execution of code inside that for loop. There is a continue keyword as well which means resume or continue the execution.

An example of continue keyword usage can be seen in this code:

package main

import "fmt"

func main() {
    for i := 0; i < 10; i++ {
        if i%2 == 0 {
            continue
        }
        fmt.Println(i)
    }

}
Enter fullscreen mode Exit fullscreen mode

The output:

1
3
5
7
9
Enter fullscreen mode Exit fullscreen mode

The result of the output prints the odd numbers, this happens because inside the for loop, there is condition selection if the value of the i variable has the remainder of 2 equals zero or if the value of i is an even number, then the continue executed means continue to execute to the next loop so the value of i isn't printed out.

The usage of nested for loop is possible. The example of nested for loop usage can be seen in this code. This code prints out a stack of stars.

package main

import "fmt"

func main() {
    for i := 0; i < 5; i++ { //outer loop
        fmt.Println()
        for j := 0; j < i; j++ { //inner loop
            fmt.Print("*")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The output:

*
**
***
****
Enter fullscreen mode Exit fullscreen mode

From the example code above. The outer loop executes the code inside the outer loop and then continues to the inner loop until the execution of the code inside the outer loop is finished.

Iteration with for range

The iteration with for range is usually suitable for reading or iterating many data over an array or slice (slice in Go means the data structure that is similar to an array but has a more flexible size). The usage of for range can be seen in this code example.

package main

import "fmt"

func main() {
    data := [5]int{1, 2, 3, 4, 5} //declares an array of int
    for i, v := range data {
        fmt.Println("index: ", i, "value: ", v)
    }

}
Enter fullscreen mode Exit fullscreen mode

The output:

index:  0 value:  1
index:  1 value:  2
index:  2 value:  3
index:  3 value:  4
index:  4 value:  5
Enter fullscreen mode Exit fullscreen mode

From the example code above, the structure of for range loop is like this :

  • Variables: i, v means that retrieves index and value from an array called data. The naming conventions aren't restricted to i and v. It could be replaced with idx and val or other suitable variable names.
  • range keyword: := range data means the variable data is the target to retrieve the index or value.

The index can be ignored by using the _ notation in Go. The example code can be seen below. This code calculates the average of numbers that are stored inside a slice called data.

package main

import "fmt"

func main() {
    data := []int{1, 2, 3, 4, 5, 6, 7} //declares a slice of int
    sum := 0                           //declares sum variable
    for _, val := range data { //ignore index with _ notation
        sum += val
    }
    fmt.Println("The sum result is: ", sum)

}
Enter fullscreen mode Exit fullscreen mode

The output:

The sum result is:  28
Enter fullscreen mode Exit fullscreen mode

Based on the code example above, the value called val in this case is a value from the data variable. Each value is added to the sum variable.

Notes

  • These are the examples of operators that can be used in Go.
Operator Equivalent Expression
+= var += 2 equals var = var + 2
-= var -= 2 equals var = var - 2
*= var *= 2 equals var = var * 2
/= var /= 2 equals var = var / 2
%= var %= 2 equals var = var % 2
++ var++ equals var = var + 1
-- var-- equals var = var - 1

Other available operators can be seen here

  • The combination of for and for range is possible. The example is like this:
package main

import "fmt"

func main() {
    data := [][]int{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
    }

    for _, v := range data {
        fmt.Println("Data: ", v)
        for i := 0; i < len(v); i++ {
            fmt.Println("\tDivided by 2:", v[i]/2)
        }
    }

}
Enter fullscreen mode Exit fullscreen mode

Output:

Data:  [1 2 3]
        Divided by 2: 0
        Divided by 2: 1
        Divided by 2: 1
Data:  [4 5 6]
        Divided by 2: 2
        Divided by 2: 2
        Divided by 2: 3
Data:  [7 8 9]
        Divided by 2: 3
        Divided by 2: 4
        Divided by 2: 4
Enter fullscreen mode Exit fullscreen mode

I hope this article helps to learn the Go programming language. If you have any thoughts or feedback, you can write it in the discussion section below.

Top comments (0)