Array Loop Boundary Error
The calculateAverage method below is intended to compute the average of the values in an integer array.
public class AverageCalculator {
public static double calculateAverage(int[] arr) {
int sum = 0;
for (int i = 0; i <= arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}
}
Which statement best describes an error in the method?
A
The method returns an integer value due to integer division, causing precision issues.
B
The method should use an enhanced-for loop to correctly accumulate the sum.
C
The loop condition uses ‘<=’ instead of ‘<’, resulting in an ArrayIndexOutOfBoundsException.
D
The variable ‘sum’ is not initialized properly before the loop.
Question Leaderboard
Not enough data yet to show leaderboard.
