static int firstPositive(int[] A, int n) { if(n == 0) return 0; } else { int x = firstPositive(A,n-1); if(x != 0) { return x; } else if(A[n-1] > 0) { return A[n-1]; } else { return 0; } } }
Another approach is to create a helper method with an extra parameter.
// firstPositiveHelp(A,i,n) yields // the first positive number in list // A[i], …, A[n-1]. If none of those // are positive, it returns 0. static int firstPositiveHelp(int[] A, int i, int n) { if(i >= n) { return 0; } else if(A[i] > 0) { return A[i]; } else { return firstPositiveHelp(A, i+1, n); } } static int firstPositive(int[] A, int n) { return firstPositiveHelp(A, 0, n); }