Ebooks

Go for loop

Go for loop tutorial shows how to create loops in Golang with for statement. There are three forms of for loops in Go.

Go for statement

The for statement specifies repeated execution of a block. There are three forms of the for statement: the classic C-style for statement, the single condition for statement, and the for statement with the range clause.

Go for loop examples

The following examples show the three available for forms in Golang.

for_loop.go
package main

import "fmt"

func main() {

    sum := 0

    for i := 0; i < 10; i++ {
        sum += i
    }
    
    fmt.Println(sum)
}

This is the classic C-style for statement. The program calculates the sum of values 1..9.

for i := 0; i < 10; i++ {
    sum += i
}

The for statement consists of three parts: the initialization, the condition, and the increment. The initialization part is executed only once. The body of the for statement is executed when the condition is true. If the condition returns false, the for loop is terminated. After the statements in the block are executed, the for loop switches to the third part, where the counter is incremented. The cycle continues until the condition is not true anymore. Note that is it possible to create endless loops.

$ go run for_loop.go 
45

The sum of values 1..9 is 45.

for_loop2.go
package main

import "fmt"

func main() {

    sum := 0
    i := 9

    for i > 0 {
        
        sum += i
        i--
    }

    fmt.Println(sum)
}

This is the single condition for statement in Go. We sum the values 9..1. In this example we define the i counter variable.

$ go run for_loop2.go 
45

This is the output.

for_loop3.go
package main

import "fmt"

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

    sum := 0
    
    for _, num := range nums {
        sum += num
    }

    fmt.Println(sum)
}

This example uses the range clause with the for statement.

nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}

We define an array of values.

for _, num := range nums {
    sum += num
}

We iterate over the array with the range clause. The range returns the index and the value in each iteration. Since we do not use the index, we specify the discard _ operator. (The Golang documentation calls it the blank identifier.)

In this tutorial, we have covered for loops in Golang.

List all Go tutorials.