Junior — Middle
In what ways have you iterated over elements in an array?
sobes.tech AI
Answer from AI
Iterating over elements in an array can be done in various ways, depending on the programming language and the task. Here are some common methods:
- For loop with index — a classic way to iterate over elements by index.
for i := 0; i < len(arr); i++ {
fmt.Println(arr[i])
}
- For range loop (in Go) — a convenient way to iterate over elements with access to index and value.
for index, value := range arr {
fmt.Println(index, value)
}
-
Recursion — sometimes used for array traversal, especially if complex logic needs to be performed.
-
Higher-order functions (like map, filter in other languages) — for iteration with function application; in Go, you can use loops or third-party libraries.
The choice of method depends on the task: whether the index is needed, whether elements need to be modified, and the importance of code readability.