Search code examples
javaprefix

Java beginner advancing sum in array


My program is supposed to take a provided array and create a new array where each element is the sum of the previous elements in original array. For example element one in new array is element one in original array. Element two in new array is sum of element one an element two in original array. Element three in new array is sum of elements one, two and three in original array. I wrote this but I know it is incomplete. Please guide.

public class PrefixSum
    {
    public static void main(String[] args)
    {
        int[] array = new int[]{0,5,1,-3,2,0,4};
        int[] newArray = new int[7];
        int x = 0;
        for(int i = 0; i < array.length; i++)
        {
            x = array[i];      
            x = x + i;
        }
        newArray[0] = 0;
        System.out.println(" " + newArray[x]);
    }
}

Solution

  • You may Debug this code in order to understand the changes.

    public static void main(String[] args)
    {
        int[] array = new int[]{0,5,1,-3,2,0,4};
        int[] newArray = new int[7];
        int x = 0;
        for(int i = 0; i < array.length; i++)
        {
            x += array[i];      
            newArray[i] = x;
        }
    }