Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing recursive java methods

Tags:

java

recursion

I am reading a book called "Think Java: How to think like a Computer Scientist", and I recently covered recursive methods.

public static void countdown(int n)
{
  if (n == 0) {
      System.out.println("Blastoff!");
  } else {
      System.out.println(n);
      countdown(n - 1);
  }
}

This would be a normal recursive method used to count down to 0 and I understand what is happening, but if you make the recursive call before the System.out.println like this

public static void countdown(int n)
{
  if (n == 0) {
      System.out.println("Blastoff!");
  } else {
      countdown(n - 1);
      System.out.println(n);
  }
}

it counts the opposite way, so If I gave the argument 3 for both of these conditional statements the 1st one goes "3, 2, 1, Blastoff!" but the 2nd 1 goes "Blastoff, 1 ,2 ,3".... I don't understand how this works, can someone try to explain what is happening in this code that makes it count in the opposite way?

like image 499
Tyler G Avatar asked Jun 08 '26 05:06

Tyler G


2 Answers

I'll try to visualize it for you.

First method

countdown(3)                (first call)
"3"                         (sysout)
    countdown(3-1)          (second call)
    "2"                     (sysout)
        countdown(2-1)      (third call)
        "1"                 (sysout)
            countdown(1-1)  (fourth call)
                "Blastoff!" (n == 0)

Second method

countdown(3)                (first call)
    countdown(3-1)          (second call)
        countdown(2-1)      (third call)
            countdown(1-1)  (fourth call)
                "Blastoff!" (n == 0. going back up call stack)
            "1"             (sysout)
        "2"                 (sysout)
    "3"                     (sysout)
like image 140
Eric Guan Avatar answered Jun 10 '26 18:06

Eric Guan


Think of it this way... In the first case you will always print before going down the next function, so...

countdown(3)
  System.out.println(3)
  countdown(2)
    System.out.println(2)
    countdown(1)    
      System.out.println(1)
      countdown(0)
        System.out.println("Blastoff")

Result: 3 2 1 Blastoff

In the second case, because you print it first, your run will go all the way down the recursion until the base case to start printing...

countdown(3)
  countdown(2)
    countdown(1)
      countdown(0)
      System.out.println("Blastoff")
    System.out.println(1)
  System.out.println(2)
System.out.println(1)

Result: 1 2 3 Blastoff

Recursion is tough! I hope I helped :)

like image 35
Arthur Ceccotti Avatar answered Jun 10 '26 17:06

Arthur Ceccotti