Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively pass counter variable in Java

I have a function which calls itself recursively:

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

    return counter;
}

From main method I call function with:

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

I expect such 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 function always returns 1 and I have no idea why.

like image 754
Edward Ruchevits Avatar asked Sep 06 '26 01:09

Edward Ruchevits


1 Answers

You're passing the value of counter, not the variable itself. Your recursive call can't modify the value of counter in the outer invocation. Java is pass-by-value.

One possible solution is to do

 counter = foo(num, counter);

in the recursive call. Or, alternately, just return foo(num, counter), since you don't do anything with counter afterwards except return it.

like image 124
Louis Wasserman Avatar answered Sep 07 '26 14:09

Louis Wasserman