Hi I'm just learning recursion and I am trying to write a recursive program in Java to find the sum of all positive elements in an array. Using : here are the expected outputs:
0 5 7 3 0 17
import java.util.Arrays;
public static void main(String[] args) {
int[] list0 = new int[] {};
int[] list1 = new int[] { 5 };
int[] list2 = new int[] { 3, 4 };
int[] list3 = new int[] { -2, 3, -4 };
int[] list4 = new int[] { -1, -2, -4, -5 };
int[] list5 = new int[] { 6, 1, 2, -3, 8 };
}
public static int sumOfPositivesRecursive (int[] a) {
return sumOfPositivesHelper(a, a.length);
}
public static int sumOfPositivesHelper(int[] a, int n) {
if(n == 0) {
return 0;
}
System.out.println(n);
int total = 0;
if(a[n-1] > 0) {
total += a[n-1];
sumOfPositivesHelper(a, n-1);
}
return total;
}
My output: 0 5 4 0 0 8, only seems to check the last element the first time and never loops through again. Please help I know I am doing something wrong with the recursive call. Thanks all.
sumOfPositivesHelpershould call itself, which it is not doing at the moment.