| preferred AP College board partner for AP classes
AP Computer Science A/Unit 6: Array
Start Practice TestPractice Test
About Exam
easy Solved by 4 students
Array Loop Boundary Error
< Prev
Next >

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.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: [email protected]|Privacy Policy