Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Understanding Recursion

Tags:

java

recursion

Can someone please explain to me why this prints out 1 2 3 4 5? I figured it would print out 4 3 2 1 0 but my book and eclipse both say I'm wrong.

public class whatever {

    /**
     * @param args
     */
    public static void main(String[] args) {
        xMethod(5);

    }

    public static void xMethod(int n){
        if (n>0){
            xMethod(n-1);
            System.out.print(n + " ");
        }
    }


}
like image 483
BluceRee Avatar asked Apr 11 '13 06:04

BluceRee


People also ask

How do you explain recursion in Java?

In Java, a method that calls itself is known as a recursive method. And, this process is known as recursion. A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.

What is the easiest way to understand recursion?

A recursive function always has to say when to stop repeating itself. There should always be two parts to a recursive function: the recursive case and the base case. The recursive case is when the function calls itself. The base case is when the function stops calling itself.

Is recursion in Java hard?

Recursion is not hard, whereas thinking recursively might be confusing in some cases. The recursive algorithm has considerable advantages over identical iterative algorithm such as having fewer code lines and reduced use of data structures.


3 Answers

It is pretty simple, these are the calls

main
   xMethod(5)
      xMethod(4)
          xMethod(3)
             xMethod(2)
                 xMethod(1)
                     xMethod(0)
                 print 1
             print 2
          print 3
      print 4
  print 5

So you see the prints are 1,2,3,4,5

like image 158
ilomambo Avatar answered Oct 16 '22 17:10

ilomambo


It's the result of the call stack. Here's what it would look like after a call with n = 5. Rotate your head about 180 degrees, since the bottom of this call chain is actually the top of the stack.

  • xMethod(5)
    • xMethod(4)
      • xMethod(3)
        • xMethod(2)
          • xMethod(1)
            • xMethod(0)

In a recursive call, you have two cases - a base case and a recursive case. The base case here is when n == 0, and no further recursion occurs.

Now, what happens when we start coming back from those calls? That is, what takes place after the recursive step? We start doing System.out.print(). Since there's a condition which prevents both recursion and printing when n == 0, we neither recurse nor print.

So, the reason that you get 1 2 3 4 5 as output is due to the way the calls are being popped from the stack.

like image 37
Makoto Avatar answered Oct 16 '22 17:10

Makoto


It first call itself recursively and only when the recursive call finishes it prints. So think about which call finishes first - it's when n = 0. Then n = 1, etc.

It's a stack and you print after taking from the stack (after the recursion call), so the order is reversed. If you printed before putting on the stack, then the order is preserved.

like image 31
Petar Ivanov Avatar answered Oct 16 '22 17:10

Petar Ivanov