0

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.

3 Answers 3

2

As written, the call tree expands to:

sum(0, 5)
0 + sum(3, 4)
0 + 3 + sum(2, 3)
0 + 3 + 2 + sum(7, 2) 
0 + 3 + 2 + 7 + sum(6, 1)
0 + 3 + 2 + 7 + 6 + sum(4, 0)
0 + 3 + 2 + 7 + 6 + 0

sum(4, 0) meets the condition index==0 so it returns 0. It should return number, which would be 4.

if (index==0){
    return number;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You are skipping the first element of the array in your sum. Return array[0] when you reach the end of the recursion :

  private static int sum(int number, int index){

    if (index==0){
        return array[0];
    }
    return number + sum(array[index-1], index-1) ;

  }

Comments

1

You are not adding the value from the first position in the array.

Instead of :

if (index==0){
    return 0;
}

try returning array[index] or number instead of 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.