0
0
Goprogramming~20 mins

Accessing array elements in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of accessing array element by index
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
    arr := [4]int{10, 20, 30, 40}
    fmt.Println(arr[2])
}
A20
B40
C30
DIndex out of range error
Attempts:
2 left
💡 Hint
Remember that Go arrays are zero-indexed, so the first element is at index 0.
Predict Output
intermediate
2:00remaining
Accessing last element of an array
What will this Go program print?
Go
package main
import "fmt"
func main() {
    arr := [5]string{"a", "b", "c", "d", "e"}
    fmt.Println(arr[len(arr)-1])
}
Ae
Ba
Cd
DIndex out of range error
Attempts:
2 left
💡 Hint
len(arr) gives the number of elements. The last index is length minus one.
Predict Output
advanced
2:00remaining
What error occurs when accessing out-of-bounds index?
What error does this Go program produce when run?
Go
package main
func main() {
    arr := [3]int{1, 2, 3}
    _ = arr[3]
}
Ano error, prints 0
Bpanic: runtime error: index out of range [3] with length 3
Ccompile error: invalid array index
Dpanic: nil pointer dereference
Attempts:
2 left
💡 Hint
Array indices must be within 0 to length-1. Accessing index 3 in a 3-element array is invalid.
🧠 Conceptual
advanced
2:00remaining
Understanding array element access with variables
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
    arr := [3]int{5, 10, 15}
    i := 1
    fmt.Println(arr[i])
    i = 2
    fmt.Println(arr[i])
}
A15\n10
B5\n10
Cruntime error: index out of range
D10\n15
Attempts:
2 left
💡 Hint
The variable i changes before the second print, so the index changes.
🔧 Debug
expert
3:00remaining
Identify the cause of the runtime error
This Go program crashes with a runtime error. What is the cause?
Go
package main
import "fmt"
func main() {
    arr := [2]int{7, 8}
    for i := 0; i <= len(arr); i++ {
        fmt.Println(arr[i])
    }
}
AThe loop condition uses <= instead of < causing out-of-bounds access
BArray is not initialized properly
Cfmt.Println cannot print array elements
DVariable i is not declared
Attempts:
2 left
💡 Hint
Check the loop boundary and valid indices for the array.