I can't quite figure out what's happening inside this method when I call it with 2 as argument.
public int foo(int i) {
if (i > 0) {
System.out.println(”i: ” + foo(i - 1));
}
return i;
}
This method returns two i.
1) i:0
2) i:1
I tried to understand this way. When the method is called with foo(2), the value of i is 2 and that is greater than zero. So it passes the if test. And then the method recalls itself in the print method; foo(2-1) which is foo(1). And now the value of i is 1 which again passes the if test; and in the print method foo(1-1) becomes foo(0) which does not pass the if test, so it returns the value of i which is zero now. What I don't understand here is where the second value of i which is 1 come from.
I ask for your help. Thank you.
What I don't understand here is where the second value of i which is 1 come from.
Regardless of whether or not the method recurses, it always returns i
. So a call of foo(2)
will always return 2, even though it recurses while printing.
The output message here is confusing because it's not printing i
. It may help you to understand if you change it to:
public int foo(int i) {
if (i > 0) {
int recurse = foo(i - 1);
System.out.println("i: " + i + "; foo(i - 1): " + recurse);
}
return i;
}
Note that you'll get the result in "reverse" order because it'll print the result of calling foo(1)
while still within foo(2)
.
See more on this question at Stackoverflow