Iterating Over Arrays
Start with Iterating Over Arrays
Iteration lets you process each array element without repeating nearly identical statements. Go supports both index-based loops and range.
What you’ll learn
- Explain the main purpose of iterating over arrays.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
An index-based loop uses for i := 0; i < len(a); i++ to select positions. A range loop uses for index, value := range a. In an array range loop, the value is the element value and changing that local variable does not update the original array.
If you intend to modify elements, iterate indexes and assign through a[i]. Use _ when you do not need one of the values returned by range.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
marks := [4]int{40, 50, 60, 70}
sum := 0
for _, mark := range marks {
sum += mark
}
for i := range marks {
marks[i] += 5
}
fmt.Println("Total before bonus:", sum)
fmt.Println("After bonus:", marks)
}
Output
Total before bonus: 220
After bonus: [45 55 65 75]Trace what the program does
The first range loop visits 40, 50, 60 and 70 and records a sum of 220. The second loop ranges over indexes and adds five directly to each array element. The final array has values 45, 55, 65 and 75.
Avoid common mistakes
- Assigning to the range value variable does not write into the array element.
- Do not use
i <= len(a); index len(a) is out of bounds.
Try it yourself
Change the bonus to 10 and calculate the new average by iterating the modified array.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Iterating Over Arrays in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.