DEV Community

nadirbasalamah
nadirbasalamah

Posted on

Golang tutorial - 4 Control Flow (Iteration)

When creating a software or program, usually there are repetitive instructions or code to complete certain task. This repetitive or iterative instructions 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 suitable for iterating data in array or slice.
for index, value := range variable {...}

Iteration with for loop

The example of for loop usage can be seen in this 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 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 customize that gives the same result, the customization of for loop could 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, there is a break keyword. break keyword means 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.

The 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 output is prints the odd numbers, this happens because inside the for loop there is condition selection if the value of i variable has 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 outer loop then continue to the inner loop until the execution of code inside outer loop is finished.

Iteration with for range

The iteration with for range usually suitable for reading or iterating many data over array or slice (slice in Go means the data structure that similiar with array but has 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 retrieve index and value from array that called data. The naming conventions isn'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 _ notation in Go. The example code can be seen below. This code calculate the average of numbers that stored inside 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 code example above, the value called val in this case is a value from data variable. Each value added to sum variable.

Notes

  • These are the example 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 helpful for helping to learn the Go programming language. If you have any thoughts or feedbacks, you can write it in the discussion section below.

Discussion (0)