Dave
Dave

Reputation: 131

Recursive method with incorrect return value

This recursive method seems to be adding to sum. For some reason when it comes to returning the sum value, sum is equal to 4, not 10, the value it should be. Why is sum not equal to 10? I am just testing the method to see if it works, the array will change.

public class TestMeanVal {
    public static void main(String[] args){
        int[] intArray = new int[] {1,2,3,4};
        System.out.println(meanRec(intArray, intArray.length-1, 0));
    }



    static double meanRec(int[] array, int b, int g){
        int sum = g;
        if (c.length == 1){
            return c[0]/1.0;
        }else if(b >= 0){
            sum += c[b];
            b--;
            meanRec(c,b, sum);
        }
        return sum/c.length;
    }
}

Upvotes: 1

Views: 199

Answers (1)

Bewusstsein
Bewusstsein

Reputation: 1621

You need to

 return meanRec(c, b, sum);

otherwise it'll recurse, but always return sum/c.length of the first invocation.

Upvotes: 2

Related Questions