Comparing Array Summation Loops
A teacher writes two methods to compute the sum of an array: one using a traditional for-loop and the other using an enhanced-for-loop. Which statement is true about their outputs?
public class Main {
public static int sumTraditional(int[] arr) {
int total = 0;
for (int i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
public static int sumEnhanced(int[] arr) {
int total = 0;
for (int num : arr) {
total += num;
}
return total;
}
public static void main(String[] args) {
int[] data = {10, 20, 30};
System.out.println(sumTraditional(data));
System.out.println(sumEnhanced(data));
}
}
A
One method computes a sum of 0 while the other computes 60.
B
The traditional loop causes an ArrayIndexOutOfBoundsException.
C
They both correctly compute the sum and output 60.
D
The enhanced-for-loop fails to iterate properly over the array.
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | imeanbusinessreplit | 1 | 1 | 0m 00s | 100 |
| #2 | gorkemakyuz201075 | 1 | 1 | 0m 33s | 67 |
| #3 | bommasam000 | 2 | 4 | 7m 02s | -242 |
| #4 | sailajavadlamani33 | 1 | 2 | 7m 46s | -376 |
Items per page:
10
1 – 4 of 4
APFIVE