Given the code fragment:

int[] array = {1, 2, 3, 4, 5};

And given the requirements:

Process all the elements of the array in the order of entry.
Process all the elements of the array in the reverse order of entry.
Process alternating elements of the array in the order of entry.

Which two statements are true?

A. Requirements 1, 2, and 3 can be implemented by using the enhanced for loop.
B. Requirements 1, 2, and 3 can be implemented by using the standard for loop.
C. Requirements 2 and 3 CANNOT be implemented by using the standard for loop.
D. Requirement 1 can be implemented by using the enhanced for loop.
E. Requirement 3 CANNOT be implemented by using either the enhanced for loop or the standard for loop.

題解

需求 1,按照順序走訪 array 陣列物件可以使用標準的 for loop 或是增強的 for loop(即 foreach)來實作出來。程式如下:

for(int i = 0; i < array.length; ++i){
    int number = array[i];
}
for(int number : array){
}

需求 2,反向走訪 array 陣列物件只可以使用標準的 for loop 來實作。

for(int i = array.length - 1; i >= 0; --i){
    int number = array[i];
}

需求 3,使用標準的 for loop,可以間隔走訪 array 陣列物件,實作方式如下:

for(int i = 0; i < array.length; i += 2){
    int number = array[i];
}

所以選項 B 和選項 D 的敘述是正確的。