I need help with a concept that will be on my Java exam. I need to write a method that takes an array and returns a new array with each element being the sum of the elements before it. i.e the first array is {3, 2, 1, 4} and the array the method returns is {3, 5, 6, 10}
Here is my code so far:
public class testPrac1 {
public static void main(String[] args){
int[] array = {3, 2, 1, 4};
for (int value: sum(array)) {
System.out.print(value);
}
}
public static int[] sum(int[] array) {
int[] newArray = new int[array.length];
for (int i = 0; i < array.length ; i++) {
if (i == 0){
newArray[i] = array[0];
}
else
for (int j = 0; j < i; j++)
newArray[i] = (array[i] + array[j]);
}
return newArray;
}
}
And just to spice it up, how about: