Are you taking CLEP classes? Try clep.ai
| 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

Comparing Array Summation Loops

Mark
< Prev
Next >

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.

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

Question Leaderboard

Rank
User
Correct Count
Attempt Count
Total Time
Score
#1imeanbusinessreplit11 0m 00s 100
#2gorkemakyuz20107511 0m 33s 67
#3bommasam00024 7m 02s -242
#4sailajavadlamani3312 7m 46s -376
Items per page:
10
1 – 4 of 4

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy|