Prefix Sum of Array

This program calculates prefix sums of an array.

Problem Statement

Write a Java program to calculate prefix sums of an integer array.

Source Code

1 public class PrefixSum {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Prefix Sum");
4 int[] arr = {1,2,3,4,5};
5 int[] prefix = new int[arr.length];
6 prefix[0] = arr[0];
7 for(int i=1;i<arr.length;i++){
8 prefix[i] = prefix[i-1] + arr[i];
9 }
10 for(int i=0;i<prefix.length;i++){
11 System.out.println("Prefix["+i+"] = "+prefix[i]);
12 }
13 }
14 }

Program Output

Eduinq Prefix Sum
Prefix[0] = 1
Prefix[1] = 3
Prefix[2] = 6
Prefix[3] = 10
Prefix[4] = 15

Explanation

The prefix array stores the cumulative sum up to each index, starting equal to the original first element, and each subsequent value adds the current element to the previous prefix sum, demonstrating the prefix sum transformation.

Quick Links to Explore