Ok so i am just learning recursion and i am confused on one point. This is the code
public class RecursiveDemo {
public static void showRecursion (int num) {
System.out.println("Entering method. num = " + num);
if (num > 1) {
showRecursion(num - 1);
}
System.out.println("Leaving method. num = " + num);
}
public static void main(String[] args){
showRecursion(2);
}
}
The output i am getting is :
Entering method. num = 2
Entering method. num = 1
Leaving method. num = 1
Leaving method. num = 2
My question is why am i getting the output "Leaving method. num = 2
". Shouldn't it stop at "Leaving method. num = 1
" since num has already reached 1?
Once the original invocation of this method leaves the if statement, it passes to System.out.println("Leaving method. num = " + num);
. Since you invoked the message originally with value 2
, 2
is the value of num
for this part of the code.
Your code runs like this (pseudocode):
Start First Call
if statement
Start Second call
Skips if statement
Print from Second Call
End of Second Call
End of if Statement
Print From First Call
End of First Call
It looks like you have a fundamental misunderstanding of recursion.
When you call your method with (num-1)
as arguments, the parent call (the first call, in this case), retains the value num
as its argument, which is 2
, in this case.
So let's comment out the line below
//showRecursion(num - 1);
What would you get? It must be
Entering method. num = 2
Leaving method. num = 2
And if you uncomment the line above. You should get the one you had.
No.
main
will call showRecursion(2)
, which in turn will call showRecursion(1)
(so you get two "Entering" messages). At which point, the condition will fail, so no more recursion occurs. So now the program simply begins returning from each function call in turn, printing both of the "Leaving" messages.
It's because the initial call to showRecursion(2)
hasn't finished yet.
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