Recursively pass counter variable in Java

I have a function that calls itself recursively:

public int foo(int num, int counter)
{
    if (num > 0)
    {
        counter++;
        num--;
        foo(num, counter);
    }

    return counter;
}

      

From the main method, I call the function with:

System.out.println(bst.foo(3, 0));

      

I expect this behavior:

public int foo(int num, int counter)
{
    // counter = 0
    // num = 3
    if (num > 0)
    {
        counter++; // counter = 1
        num--; // num = 2
        if (num > 0)
        {
            counter++; // counter = 2
            num--; // num = 1
            if (num > 0)
            {
                counter++; // counter = 3
                num--; // num = 0
                if (num > 0)
                {
                    // don't execute as num = 0
                }
            }
        }
    }

    return counter; // return 3
}

      

But the function always returns 1

and I have no idea why.

+3


source to share


1 answer


You are passing the value counter

, not the variable itself. Your recursive call cannot change the value counter

in the outer call. Java is about bandwidth.

One possible solution is



 counter = foo(num, counter);

      

in a recursive call. Or, alternatively, simply return foo(num, counter)

, since after that, you don't do anything with counter

but return it.

+8


source







All Articles