Challenge - 5 Problems
Array Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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]) }
Attempts:
2 left
💡 Hint
Remember that Go arrays are zero-indexed, so the first element is at index 0.
✗ Incorrect
The array has elements 10, 20, 30, 40 at indices 0, 1, 2, 3 respectively. Accessing arr[2] returns 30.
❓ Predict Output
intermediate2: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]) }
Attempts:
2 left
💡 Hint
len(arr) gives the number of elements. The last index is length minus one.
✗ Incorrect
The last element is at index 4 (5-1), which is "e".
❓ Predict Output
advanced2: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] }
Attempts:
2 left
💡 Hint
Array indices must be within 0 to length-1. Accessing index 3 in a 3-element array is invalid.
✗ Incorrect
Go panics at runtime with an index out of range error when accessing arr[3].
🧠 Conceptual
advanced2: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]) }
Attempts:
2 left
💡 Hint
The variable i changes before the second print, so the index changes.
✗ Incorrect
First print accesses arr[1] which is 10, second print accesses arr[2] which is 15.
🔧 Debug
expert3: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]) } }
Attempts:
2 left
💡 Hint
Check the loop boundary and valid indices for the array.
✗ Incorrect
The loop runs from i=0 to i=2 inclusive, but arr has length 2, so arr[2] is out of range causing runtime panic.