Comparing Array Summation Loops
Consider the following Java class containing two methods, sumTraditional and sumEnhanced, designed to compute the sum of an array’s elements. Which statement accurately describes the program’s output when the main method is executed?
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
They both correctly compute the sum and output 60.
B
The traditional loop causes an ArrayIndexOutOfBoundsException.
C
The enhanced-for-loop fails to iterate properly over the array.
D
One method computes a sum of 0 while the other computes 60.
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
