Iterate over Elements of Array using For Loop
To iterate over elements of an array using for loop, use for loop with initialization of (index = 0), condition of (index < array length) and update of (index++). Inside for loop access the element using array[index].
The syntax to iterate over array arr using for loop is
</>
Copy
for i := 0; i < len(arr); i++ {
//arr[i]
}
Examples
Iterate over Elements of Integer Array
In the following program, we take an integer array arr of size 5. We iterate over the elements of this array using for loop.
example.go
</>
Copy
package main
import "fmt"
func main() {
arr := [5]int{10, 20, 30, 40, 50}
for i := 0; i < len(arr); i++ {
fmt.Println(arr[i])
}
}
Output
10
20
30
40
50
Iterate over Elements of String Array
Now, let us take a string array, and iterate over its elements.
example.go
</>
Copy
package main
import "fmt"
func main() {
arr := [5]string{"apple", "banana", "cherry"}
for i := 0; i < len(arr); i++ {
fmt.Println(arr[i])
}
}
Output
apple
banana
cherry
Conclusion
In this Go Tutorial, we learned how to iterate over elements of array using for loop in Go programming, with the help of example programs.
