0
0
Goprogramming~5 mins

Iterating over arrays in Go

Choose your learning style9 modes available
Introduction

We use iteration to look at each item in an array one by one. This helps us do something with every item, like printing or changing it.

When you want to print all items in a list of names.
When you need to add 1 to every number in a list of scores.
When you want to find the biggest number in a list of ages.
When you want to check if a certain word is in a list of words.
Syntax
Go
package main

import "fmt"

type ArrayExample struct {
    items [5]int
}

func (a *ArrayExample) Iterate() {
    for index, value := range a.items {
        fmt.Printf("Index %d has value %d\n", index, value)
    }
}

The range keyword helps us go through each item in the array easily.

You get both the index and the value of each item during iteration.

Examples
Iterate over an array with 3 numbers, printing index and value.
Go
package main

import "fmt"

func main() {
    var numbers [3]int = [3]int{10, 20, 30}
    for i, v := range numbers {
        fmt.Println(i, v)
    }
}
Iterating over an empty array does nothing, no output.
Go
package main

import "fmt"

func main() {
    var emptyArray [0]int
    for i, v := range emptyArray {
        fmt.Println(i, v) // This will not print anything
    }
}
Iterate over an array with one string element.
Go
package main

import "fmt"

func main() {
    var singleElement [1]string = [1]string{"hello"}
    for i, v := range singleElement {
        fmt.Println(i, v)
    }
}
Check and print only the first and last elements in the array.
Go
package main

import "fmt"

func main() {
    var letters [4]string = [4]string{"a", "b", "c", "d"}
    for i, v := range letters {
        if i == 0 || i == len(letters)-1 {
            fmt.Println("Edge element:", v)
        }
    }
}
Sample Program

This program creates an array of fruits and prints each fruit with its position.

Go
package main

import "fmt"

func main() {
    var fruits [5]string = [5]string{"apple", "banana", "cherry", "date", "elderberry"}

    fmt.Println("Before iteration:", fruits)

    fmt.Println("Iterating over fruits array:")
    for index, fruit := range fruits {
        fmt.Printf("Fruit at index %d is %s\n", index, fruit)
    }
}
OutputSuccess
Important Notes

Time complexity is O(n) because we visit each item once.

Space complexity is O(1) extra space since we only use a few variables.

Common mistake: forgetting that arrays have fixed size in Go, so you cannot add or remove items during iteration.

Use iteration when you want to process or check every item. For changing size, use slices instead.

Summary

Iteration lets you visit each item in an array one by one.

Use for index, value := range array to loop through arrays in Go.

Remember arrays have fixed size, so iteration is for reading or updating items, not changing size.