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


Arrays are a fundamental data structure in Go that allow you to store a fixed-size sequence of elements of the same type. One of the most common operations you will perform on an array is to iterate over its elements to process them in some way. In this article, we will discuss how to iterate over an array using a for loop in Go.

Iterating Over an Array Using a for loop in Go

In Go, you can iterate over the elements of an array using a for loop. Here is the syntax for iterating over an array using a for loop −

for index, element := range array {
   // process element
}

where array is the name of the array, index is the index of the current element, and element is the current element itself. The range keyword is used to iterate over the elements of the array.

Example

Here is an example that demonstrates how to iterate over an array of integers using a for loop −

package main

import "fmt"

func main() {
   numbers := [5]int{1, 2, 3, 4, 5}

   for index, number := range numbers {
      fmt.Printf("Index: %d, Value: %d\n", index, number)
   }
}

In this example, we define an array of numbers of 5 integers. We then use a for loop to iterate over the elements of the array, printing the index and value of each element using fmt.Printf. The output of this program will be −

Output

Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3
Index: 3, Value: 4
Index: 4, Value: 5

Conclusion

In this article, we discussed how to iterate over an array using a for loop in Go. The syntax for iterating over an array using a for loop is simple, and it allows you to process the elements of the array one by one. We also provided an example that demonstrated how to use a for loop to iterate over an array of integers and print the index and value of each element. By following the guidelines outlined in this article, you should be able to iterate over arrays in your Go programs.

Updated on: 08-May-2023

264 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements