zilcuanu
zilcuanu

Reputation: 3715

Recursive function to add elements in an array

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.

Upvotes: 0

Views: 2964

Answers (3)

aniri
aniri

Reputation: 1831

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.

Upvotes: 1

OtherDevOpsGene
OtherDevOpsGene

Reputation: 7451

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;
}

Upvotes: 2

Eran
Eran

Reputation: 393811

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) ;

  }

Upvotes: 1

Related Questions