LearnFrenzy
Sign in Take a free test

Arrays in Java · Predict the Output · Question 16

Range sums with a prefix-sum array Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 16 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] a = {3, 1, 4, 1, 5, 9, 2};
        int[] pre = new int[a.length + 1];
        for (int i = 0; i < a.length; i++) pre[i + 1] = pre[i] + a[i];
        System.out.println(Arrays.toString(pre));
        System.out.println((pre[5] - pre[2]) + " " + (pre[7] - pre[0]));     // sum of a[2..4] and of everything
    }
}
  • A [0, 3, 4, 8, 9, 14, 23, 25] 10 25 Correct
  • B [3, 4, 8, 9, 14, 23, 25] 10 25
  • C [0, 3, 4, 8, 9, 14, 23, 25] 9 25
  • D [0, 3, 4, 8, 9, 14, 23, 25] 10 23
Correct Answer: Option A

pre[i] is the sum of the first i elements, so the sum of a[l..r] is pre[r + 1] - pre[l]: 4 + 1 + 5 = 10.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links