summing elements in an array java code example
Example 1: sum numbers in array java
public class Exercise2 {
public static void main(String[] args) {
int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
for (int i : my_array)
sum += i;
System.out.println("The sum is " + sum);
}
}
Example 2: java running sum of array
class Solution {
public int[] runningSum(int[] nums) {
int[] sol = new int[nums.length];
sol[0] = nums[0];
for(int i = 1; i < nums.length; i++) {
sol[i] = sol[i-1] + nums[i];
}
return sol;
}
}