Go - Array Iteration Example

1. Introduction

Iterating over arrays is a fundamental operation in Go programming, as it allows you to access each element and perform actions with it. Go provides a straightforward method to iterate using the range clause in a for loop. This post will illustrate how to iterate over an array in Go and execute operations on its elements.

Definition

Array iteration refers to sequentially accessing each element of an array. In Go, this is commonly done using a for loop together with the range keyword, which returns both the index and the value of elements in an array.

2. Program Steps

1. Define an array with a set of values.

2. Use a for loop with range to iterate over the array.

3. Print each element's index and value during iteration.

4. Calculate the sum of all elements in the array as an example operation.

3. Code Program

package main

import "fmt"

func main() {
	// Step 1: Define an array
	numbers := [5]int{2, 4, 6, 8, 10}

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

	// Step 4: Calculate the sum of all elements
	sum := 0
	for _, value := range numbers {
		sum += value
	}
	fmt.Println("Sum of all numbers:", sum)
}

Output:

Iterating over the array:
Index: 0, Value: 2
Index: 1, Value: 4
Index: 2, Value: 6
Index: 3, Value: 8
Index: 4, Value: 10
Sum of all numbers: 30

Explanation:

1. package main - Declares the package for the Go program.

2. import "fmt" - Imports the Format package for formatted output.

3. numbers - An integer array is declared and initialized with 5 values.

4. The first for loop uses range to iterate over numbers, where index is the position of the element in the array, and value is the actual element value.

5. Within the loop, fmt.Printf prints the index and value of each element in the array.

6. The second for loop (which omits the index using _) calculates the sum of all elements in the numbers array.

7. fmt.Println outputs the total sum after the loop completes.

8. The output lists each element in the array along with its index and shows the total sum of the array's values, demonstrating how to perform array iteration and a sum operation in Go.


Comments