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
Prefix sum stores cumulative sum up to index i. - First element is same as original. - Each subsequent element adds current value to previous prefix. - Together demonstrates prefix sum transformation. Conclusion: Shows how arrays can be transformed into prefix sums.