I have written a recursive function to sum up the elements in an array. I am puzzled and confused on how the following program is behaving.
public class Recursion{
private static int array[] = new int[]{4,6,7,2,3};
public static void main(String argv[]){
int result = sum(0 , 5);
System.out.println("The result is "+result);
}
private static int sum(int number, int index){
if (index==0){
return 0;
}
return number + sum(array[index-1], index-1) ;
}
}
The above program returns 18 as the answer. Could someone please elaborate more on the above program as in where I am going wrong.