ZetCode

Go for loop

last modified August 24, 2023

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 version
go version go1.18.1 linux/amd64

We use Go version 1.18.

Go for loop examples

The following examples show the 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. It is functionally equivalent to the C while loop. We sum the values 9..1. In this example we define the i counter variable.

$ go run for_loop2.go 
45

The next example uses the range clause with the for statement.

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)
}

We calculate the sum of integer values.

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 the next example, we use the index value.

for_loop4.go
package main 

import "fmt"

func main() {

    words := []string{"sky", "cup", "cloud", "news", "water"}

    for idx, word := range words {

        fmt.Printf("%s has index %d\n", word, idx)
    }
}

We iterate over a slice of words. We print the word and its index.

$ go run for_loop4.go 
sky has index 0
cup has index 1
cloud has index 2
news has index 3
water has index 4

In the next example, we create an infinite loop.

infinite.go
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func init() {

    rand.Seed(time.Now().UnixNano())
}

func main() {
    
    for {
        
        r := rand.Intn(30)
        
        fmt.Printf("%d ", r)

        if r == 22 {
            break;
        }
    }
}

The example prints randomly values from <0, 30) in an infinite loop. We terminate the loop with the break keyword when we encounter value 22.

In this article we have covered for loops in Golang.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Go tutorials.