user4127994
user4127994

Reputation: 27

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]);
    }
}

Upvotes: 1

Views: 760

Answers (4)

List<Integer> sums = new ArrayList<>();
Stream.of(0, 5, 1, -3, 2, 0, 4).reduce((left, right) -> {
    sums.add(left + right);
    return left + right;
});

Printing sums after running yields :

[0, 5, 6, 3, 5, 5, 9]

Try it here.

Upvotes: 1

Null
Null

Reputation: 511

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;
    }
}

Upvotes: 2

Sash Sinha
Sash Sinha

Reputation: 22418

You can use a variable runningTotal to keep count of the running total like so:

import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    int[] originalArray = new int[]{0,5,1,-3,2,0,4};
    int[] sumArray = new int[originalArray.length];

    int runningTotal = 0;
    for(int i = 0; i < originalArray.length; i++){
      runningTotal += originalArray[i];
      sumArray[i] = runningTotal;
    }

    System.out.println("The originalArray is: " + Arrays.toString(originalArray));
    System.out.println("The sumArray is: " + Arrays.toString(sumArray));
  }
}

Output:

The originalArray is: [0, 5, 1, -3, 2, 0, 4]
The sumArray is: [0, 5, 6, 3, 5, 5, 9]

Try it here!

Upvotes: 4

Anton Homjak
Anton Homjak

Reputation: 31

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

}

Upvotes: 1

Related Questions