| preferred AP College board partner for AP classes
AP Computer Science A/Unit 6: Array
Start Practice TestPractice Test
About Exam
easy Solved by 7 students
Comparing Array Summation Loops
< Prev
Next >

A teacher writes two methods to compute the sum of an array: one using a traditional for-loop and the other using an enhanced-for-loop. Which statement is true about their outputs?

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

One method computes a sum of 0 while the other computes 60.

B

The traditional loop causes an ArrayIndexOutOfBoundsException.

C

They both correctly compute the sum and output 60.

D

The enhanced-for-loop fails to iterate properly over the array.

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

Question Leaderboard

Rank
User
Correct Count
Attempt Count
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
No comments yet. Be the first to comment!

AI Tutor

How can I help?

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