How to Iterate Over Arrays in Go Using Range

1. Introduction

Iterating over arrays is a common task in programming. In Go, iteration can be easily achieved using the range clause in a for loop. This approach simplifies accessing each element of the array by index and value. In this post, we will demonstrate how to use range to iterate over arrays in Go.

Definition

The range keyword in Go is used in conjunction with the for loop to iterate over slices and arrays. It returns two values on each iteration: the index and a copy of the element at that index.

2. Program Steps

1. Declare and initialize an array.

2. Iterate over the array using range in a for loop.

3. Print each element's index and value.

4. Optionally, demonstrate how to ignore the index or value if not needed.

3. Code Program

package main

import "fmt"

func main() {
	// Step 1: Declare and initialize an array
	numbers := [5]int{10, 20, 30, 40, 50}

	// Step 2 and 3: Iterate over the array with range
	fmt.Println("Array elements:")
	for index, value := range numbers {
		fmt.Printf("Index: %d, Value: %d\n", index, value)
	}

	// Optional: Ignore the index if it's not needed
	fmt.Println("\nArray values:")
	for _, value := range numbers {
		fmt.Printf("Value: %d\n", value)
	}
}

Output:

Array elements:
Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30
Index: 3, Value: 40
Index: 4, Value: 50
Array values:
Value: 10
Value: 20
Value: 30
Value: 40
Value: 50

Explanation:

1. package main - Indicates the package name for the Go program.

2. import "fmt" - Includes the Format package necessary for output operations.

3. numbers is an integer array initialized with 5 integers.

4. The for loop uses range numbers to iterate over the array. index and value are the variables that receive the index and value of the array element respectively on each iteration.

5. Inside the loop, fmt.Printf prints both the index and the value of the current array element.

6. In the optional section, the for loop uses _ to ignore the index and only value is used, which is common when the index is not required.

7. The output first displays each element with its corresponding index and then only the values of the array elements in the next section, showing two ways to use range for array iteration in Go.


Comments