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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With