Bird
Raised Fist0
Goprogramming~10 mins

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

Choose your learning style10 modes available
Concept Flow - Iterating over arrays
Start
↓
Initialize index i=0
↓
Check: i < length of array?
No→End
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.

Practice

(1/5)
1. What does the range keyword do when used with an array in Go?
easy
A. It creates a new array with copied elements.
B. It changes the size of the array during iteration.
C. It lets you loop over each element and get its index and value.
D. It sorts the array elements automatically.

Solution

  1. Step 1: Understand the role of range in loops

    The range keyword in Go is used to iterate over elements in arrays, slices, maps, and more, providing both the index and the value of each element.
  2. Step 2: Identify what range does with arrays

    When used with an array, range returns the index and the value of each element one by one, allowing you to process or read each item.
  3. Final Answer:

    It lets you loop over each element and get its index and value. -> Option C
  4. Quick Check:

    range loops with index and value [OK]
Hint: Remember: range gives index and value for each element [OK]
Common Mistakes:
  • Thinking range changes array size
  • Assuming range sorts elements
  • Believing range copies the array
2. Which of the following is the correct syntax to iterate over an array named nums in Go?
easy
A. for i, v := range nums { fmt.Println(i, v) }
B. for i in nums { fmt.Println(i) }
C. foreach i, v in nums { fmt.Println(i, v) }
D. for (i, v) in nums { fmt.Println(i, v) }

Solution

  1. Step 1: Recall Go's for-range loop syntax

    In Go, the correct way to iterate over arrays or slices is using for index, value := range array syntax.
  2. Step 2: Match the syntax with the options

    for i, v := range nums { fmt.Println(i, v) } uses for i, v := range nums, which is the correct Go syntax. Other options use invalid or non-Go syntax.
  3. Final Answer:

    for i, v := range nums { fmt.Println(i, v) } -> Option A
  4. Quick Check:

    Go uses for i, v := range array [OK]
Hint: Use 'for i, v := range array' for Go array loops [OK]
Common Mistakes:
  • Using 'for i in nums' like Python
  • Using 'foreach' which is not Go syntax
  • Using parentheses in for loop header
3. What will be the output of this Go code?
nums := [3]int{10, 20, 30}
for i, v := range nums {
    fmt.Println(i, v)
}
medium
A. 0 0 1 1 2 2
B. 10 0 20 1 30 2
C. Syntax error
D. 0 10 1 20 2 30

Solution

  1. Step 1: Understand the array and loop

    The array nums has 3 elements: 10 at index 0, 20 at index 1, and 30 at index 2. The loop uses range to get index and value.
  2. Step 2: Trace the loop output

    Each iteration prints the index and the value: first line prints "0 10", second "1 20", third "2 30".
  3. Final Answer:

    0 10 1 20 2 30 -> Option D
  4. Quick Check:

    Index and value printed in order [OK]
Hint: range returns index then value in order [OK]
Common Mistakes:
  • Swapping index and value in print
  • Expecting values as indexes
  • Thinking code has syntax error
4. Identify the error in this Go code snippet:
nums := [3]int{1, 2, 3}
for i, v = range nums {
    fmt.Println(i, v)
}
medium
A. Missing colon in 'for i, v = range nums' should be ':='
B. Using '=' instead of '==' in loop condition
C. Array declaration syntax is wrong
D. fmt.Println cannot print two variables

Solution

  1. Step 1: Check the for loop variable declaration

    In Go, when declaring variables in a for-range loop, you must use ':=' to declare and assign variables, not '='.
  2. Step 2: Identify the syntax error

    The code uses '=' instead of ':=' in for i, v = range nums, which causes a syntax error.
  3. Final Answer:

    Missing colon in 'for i, v = range nums' should be ':=' -> Option A
  4. Quick Check:

    Use ':=' to declare variables in for-range loops [OK]
Hint: Use ':=' not '=' in for-range variable declaration [OK]
Common Mistakes:
  • Using '=' instead of ':=' in for loop
  • Confusing assignment with comparison
  • Incorrect array syntax blamed
5. Given an array nums := [5]int{1, 2, 3, 4, 5}, how can you create a new slice containing only the even numbers using iteration?
hard
A. Use a for loop to change the array size and remove odd numbers.
B. Use a for-range loop to check each value and append even numbers to a slice.
C. Use range to multiply all numbers by 2 and store in a new array.
D. Use a for loop with index only and ignore values.

Solution

  1. Step 1: Understand the goal and array

    The goal is to create a new slice with only even numbers from the array nums. Arrays have fixed size, so we cannot remove elements from it.
  2. Step 2: Use for-range loop and append even values

    We iterate over nums using for _, v := range nums, check if v % 2 == 0, and append those values to a new slice.
  3. Final Answer:

    Use a for-range loop to check each value and append even numbers to a slice. -> Option B
  4. Quick Check:

    Filter with for-range and append even numbers [OK]
Hint: Filter with for-range and append to slice [OK]
Common Mistakes:
  • Trying to change array size directly
  • Ignoring values in loop
  • Multiplying instead of filtering
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard