💭 What is it?
Learners tend to believe that a loop is always needed to access an element of an array, even if the index of the respective element is already known.
int[] numbers = {180, 250, 25, -134, 0, 25};
int index = 3;
// here a loop is used to access an element with a known index
for (int i = 0; i < numbers.length; i++) {
if (i == index) {
println(numbers[i]);
}
}🛠️ Why is it incorrect?
Accessing an element of an array does not require a loop when the index of the element is already known. Arrays in Processing/Java allow random access to their elements, meaning any element can be accessed directly using its index. This access happens in constant time, irrespective of the size of the array.
Inefficient Code:
int[] numbers = {180, 250, 25, -134, 0, 25};
int index = 3;
for (int i = 0; i < numbers.length; i++) {
if (i == index) {
println(numbers[i]);
}
}Improved Code:
int[] numbers = {180, 250, 25, -134, 0, 25};
int index = 3;
println(numbers[index]);🧩 Typical errors
Students use loops to access an element of an array with a known index.
int[] numbers = {180, 250, 25, -134, 0, 25};
int index = 3;
for (int i = 0; i < numbers.length; i++) {
if (i == index) {
println(numbers[i]);
}
}🌱 Origin
Students are often overexposed to loop-based examples.
On one hand, when they try to solve new tasks, they use loops as a “blueprint” for working with arrays. This behavior often stems from a general insecurity in handling arrays, leading students to rely on previously shown examples as templates for solving other problems. As these examples often involve loops, they reinforce the belief that loops are always necessary.
On the other hand, students may misunderstand the conceptual nature of arrays, viewing them as sequentially iterable structures where each element must be accessed in order. As a result, students fail to recognize that arrays allow random access to elements through direct indexing.
🧩 Related Exercises
🧑🏫 Teaching Opportunities
Helpful Exercises:
A student tries to access the value of a specific element of an array, but the code is inefficient. Try to improve the code, searching for a more efficient solution.
int[] numbers = {4, 139, 25, 10};
int index = 2;
for (int i = 0; i < numbers.length; i++) {
if (i == index) {
println(numbers[i]);
}
}Peer Instruction Quizzes:
🧩 Peer Instruction Quiz
In which situation is a loop necessary to access array elements?
🧩 Peer Instruction Quiz
Given the following code, how can this code be improved?






