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.
You’re passing the value of
counter, not the variable itself. Your recursive call can’t modify the value ofcounterin the outer invocation. Java is pass-by-value.One possible solution is to do
in the recursive call. Or, alternately, just
return foo(num, counter), since you don’t do anything withcounterafterwards except return it.