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.
Iterating over arrays in 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.
package main import "fmt" func main() { var numbers [3]int = [3]int{10, 20, 30} for i, v := range numbers { fmt.Println(i, v) } }
package main import "fmt" func main() { var emptyArray [0]int for i, v := range emptyArray { fmt.Println(i, v) // This will not print anything } }
package main import "fmt" func main() { var singleElement [1]string = [1]string{"hello"} for i, v := range singleElement { fmt.Println(i, v) } }
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) } } }
This program creates an array of fruits and prints each fruit with its position.
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) } }
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.
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.