Array Loop Boundary Error
What error is present in the calculateAverage method above?
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;
}
}
A
The loop condition uses ‘<=’ instead of ‘<’, resulting in an ArrayIndexOutOfBoundsException.
B
The method should use an enhanced-for loop to correctly accumulate the sum.
C
The variable ‘sum’ is not initialized properly before the loop.
D
The method returns an integer value due to integer division, causing precision issues.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE