0
0
Goprogramming~20 mins

Iterating over arrays in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of range loop with index and value
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
  arr := [3]int{10, 20, 30}
  for i, v := range arr {
    fmt.Printf("%d:%d ", i, v)
  }
}
A0:10 1:20 2:30
B10:0 20:1 30:2
C0 10 1 20 2 30
D10 20 30
Attempts:
2 left
💡 Hint
Remember that range returns index and value in that order.
Predict Output
intermediate
2:00remaining
Output when ignoring index in range loop
What will this Go program print?
Go
package main
import "fmt"
func main() {
  arr := [4]string{"a", "b", "c", "d"}
  for _, v := range arr {
    fmt.Print(v)
  }
}
Aabcd
B0123
Ca b c d
D[a b c d]
Attempts:
2 left
💡 Hint
The underscore _ ignores the index, so only values are printed.
🔧 Debug
advanced
2:00remaining
Identify the error in this array iteration
What error will this Go code produce when compiled?
Go
package main
import "fmt"
func main() {
  arr := [3]int{1, 2, 3}
  for i, v := range arr {
    fmt.Println(i + v)
  }
  fmt.Println(arr[3])
}
Acompile error: invalid array index 3 (out of bounds)
Bno error, prints 1 3 5
Cprints 1 3 5 and then 0
Druntime panic: index out of range
Attempts:
2 left
💡 Hint
Check the array length and the index used after the loop.
Predict Output
advanced
2:00remaining
Output of modifying array elements inside range loop
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
  arr := [3]int{1, 2, 3}
  for i, v := range arr {
    v = v * 2
    fmt.Print(v, " ")
  }
  fmt.Println()
  fmt.Println(arr)
}
A
1 2 3 
[1 2 3]
B
2 4 6 
[2 4 6]
C
2 4 6 
[1 2 3]
Dcompile error
Attempts:
2 left
💡 Hint
Remember that v is a copy of the element, not the element itself.
🧠 Conceptual
expert
2:00remaining
Number of iterations in nested array loops
Given this Go code, how many times will the innermost print statement execute?
Go
package main
import "fmt"
func main() {
  arr := [2][3]int{{1,2,3},{4,5,6}}
  count := 0
  for _, inner := range arr {
    for i := range inner {
      fmt.Println(inner[i])
      count++
    }
  }
  fmt.Println("Total:", count)
}
A5
B6
C3
D2
Attempts:
2 left
💡 Hint
Count elements in each inner array and multiply by number of outer arrays.