How to iterate over an Array using a for loop in Golang

An Array is a data structure that holds a specific number of elements and cannot grow or shrink. It can also be defined as a data structure that consists of a collection of elements of a single type and can hold more than one value at a time.

Different data types such as Integer, String, and Boolean are handled as elements in an array.

We need to iterate over an array when certain operations will be performed on it. A for loop is best suited for this purpose.

The syntax to iterate over an array using a for loop is shown below:

for i := 0; i < len(arr); i++ {
// do something
}

How to iterate over an array of integers

The code below demonstrates the iteration over an array of integers. The array has a size of 5 and we iterate over the elements using a for loop.

package main
import "fmt"
func main() {
arr := [5]int{11, 12, 13, 14, 15}
for i := 0; i < len(arr); i++ {
fmt.Println(arr[i])
}
}

In the code above, the variable i is initialized as 0 and is incremented after every iteration until it reaches a value equal to the array’s length. The Println statement prints the elements at each index of the array one after the other.

The code above will produce the following output:

11
12
13
14
15

How to iterate over an array of strings

The code below iterates over an array of strings. The range keyword sets the scope of iteration up to the length of the array. The variables index and element store the indices and values of the array, respectively.

package main
import "fmt"
func main() {
arr := [3]string{"Jack", "James", "Jim"}
for index, element := range arr {
fmt.Println("Index", index, "has a value of", element)
}
}

The output of the code above is:

Index 0 has a value of Jack
Index 1 has a value of James
Index 2 has a value of Jim

Free Resources