0
0
Goprogramming~10 mins

Iterating over arrays in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Iterating over arrays
Start
Initialize index i=0
Check: i < length of array?
NoEnd
Yes
Access array[i
Process element
Increment i (i = i+1)
Back to Check
Start with index 0, check if it's less than array length, process element, increment index, repeat until done.
Execution Sample
Go
package main

import "fmt"

func main() {
    arr := [3]int{10, 20, 30}
    for i := 0; i < len(arr); i++ {
        fmt.Println(arr[i])
    }
}
This code prints each element of the array one by one.
Execution Table
IterationiCondition (i < len(arr))ActionOutput
100 < 3 (true)Print arr[0] = 1010
211 < 3 (true)Print arr[1] = 2020
322 < 3 (true)Print arr[2] = 3030
433 < 3 (false)Exit loop
💡 i reaches 3, condition 3 < 3 is false, loop ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
i01233
arr[i]arr[0]=10arr[1]=20arr[2]=30--
Key Moments - 3 Insights
Why does the loop stop when i equals the length of the array?
Because the condition i < len(arr) becomes false at that point, as shown in execution_table row 4, so the loop exits.
Why do we start the index i at 0 instead of 1?
Array indexes in Go start at 0, so the first element is at arr[0], as seen in execution_table row 1.
What happens if we try to access arr[i] when i equals the array length?
It causes an error because arr[len(arr)] is out of bounds; the loop condition prevents this by stopping before i reaches len(arr).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of i during the third iteration?
A2
B3
C1
D0
💡 Hint
Check the 'i' column in execution_table row 3.
At which iteration does the loop condition become false?
AIteration 2
BIteration 3
CIteration 4
DIteration 1
💡 Hint
Look at the 'Condition' column in execution_table row 4.
If the array had 5 elements instead of 3, how many times would the loop run?
A3 times
B5 times
C4 times
D6 times
💡 Hint
The loop runs once for each index from 0 up to length-1, so equal to array length.
Concept Snapshot
Go arrays start at index 0.
Use for loop: for i := 0; i < len(arr); i++ {}
Access elements with arr[i].
Loop runs while i < length.
Stops before i equals length to avoid errors.
Full Transcript
This visual trace shows how to iterate over arrays in Go. We start with index i at 0, check if i is less than the array length, then access and print arr[i]. After processing, we increment i by 1 and repeat. The loop stops when i equals the array length, preventing out-of-bounds errors. The variable tracker shows i increasing from 0 to 3, and the output prints each array element in order.