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 value2,2is the value ofnumfor this part of the code.Your code runs like this (pseudocode):
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 valuenumas its argument, which is2, in this case.