Which of the following can loop through an array without referring to the elements by index?

Which of the following can loop through an array without referring to the elements by index?

A. do-while loop

B. for (traditional)

C. for-each

D. while

Answer:

C. for-each

Explanation:

While a traditional for loop often loop through an array, it uses an index to do so, making Option B incorrect. 

The for-each loop goes through each element, storing it in a variable. Option C is correct.

The "for-each" loop (also known as the enhanced for loop) can loop through an array without referring to the elements by index. In languages such as Java, this loop is specifically designed for iterating over collections and arrays.

Here is an example in Java:

int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
    System.out.println(number);
}

In this example, the variable "number" takes on the value of each element in the "numbers" array, one at a time, from the first to the last, without ever needing to use an index variable.


Comments