Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion output ambiguity

Tags:

java

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?

like image 837
armitage Avatar asked Jul 29 '11 02:07

armitage


4 Answers

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.

like image 86
Zéychin Avatar answered Nov 04 '22 23:11

Zéychin


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.

like image 20
Tae-Sung Shin Avatar answered Nov 04 '22 23:11

Tae-Sung Shin


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.

like image 42
Oliver Charlesworth Avatar answered Nov 05 '22 00:11

Oliver Charlesworth


It's because the initial call to showRecursion(2) hasn't finished yet.

like image 39
rfk Avatar answered Nov 04 '22 23:11

rfk