简体   繁体   中英

Why does recursion act differently for different placements of recursive call

I'm trying to understand how recursion works. I have two codes that have different outputs due to the placement of the recursive call. I understand that it's SUPPOSED to have different outputs, but I don't understand WHY the output is what it is.

Code 1 (recursive call placed AFTER print):

public class Test {
    public static void main(String[] args) {
        xMethod(5);
    }

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

The above output is 5 4 3 2 1. I understand why I get this output. It's because first, 5 is printed, then 5 is deducted by 1 and 4 is printed, and so on.

What is I don't understand is the output of the following code, when the recursive call is place before the print.

Code 2 (recursive call placed before print):

public class Test {
    public static void main(String[] args) {
        xMethod(5);
    }

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

The above output is 1 2 3 4 5. I can't figure out why I get this output. I would imagine the output to be 4 3 2 1, as the 5 is deducted, then printed as 4, and so on. But this obviously is not the case.

Can someone help me understand what is going on in the recursive process?

In first case printing is done and then call happens.

In second case calls happens in this way :

x(5) -> x(4) -> x(3) -> x(2) -> x(1) -> print(1) ->print(2) ->print(3) ->print(4) -> print(5)

Printing starts from the end call.

x(5)
  |
  x(4)                            print(5)
    |                             | 
    x(3)                    print(4)
      |                     |
      x(2)            print(3)
        |             |
        x(1)    print(2)
          |     | 
          print(1)  

In case of first

  print(5)
  x(5)
  |
  print(4)
  x(4)                            
    |
    print(3)                             
    x(3)                    
      |
      print(2)                     
      x(2)            
        | 
        print(1)  
        x(1)    

In the second code the line: System.out.print(n + " "); will not be executed unless all the recursive calls get completed.

The recursive function is calling itself before executing the print line.

In the first script,

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

The output is printed before the step into the recursive call.

In the second script,

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

The function keeps stepping "into" the recursion ie once xMethod(n-1) is called, the line below it is not executed ie the print statement. And this keeps happening until the last recursive call has been executed ie when x == 1, then the call goes backward and starts all the print statements beginning with the print statement for x == 1, then the print statement for x == 2 etc until the last print statement for the first call.

I have listed a stack trace of your second snippet's execution flow (Wish I could have aligned the table and 4 columns better)

If you step through your program when debugging it, you will obtain to a similar stack trace that tells you the value of the variables as you step through the program's execution flow, tabulated similar to the info listed below:

Stack trace| Value of Variable n | Statement executed | Output

main
    xmethod(5)          5               xmethod(4)
     xmethod(4)         4               xmethod(3)
      xmethod(3)        3               xmethod(2)
       xmethod(2)       2               xmethod(1)
        xmethod(1)      1               xmethod(0)
         xmethod(0)     0               
        xmethod(1)      1            System.out.print(1 + " ")                1
       xmethod(2)       2            System.out.print(2 + " ")                1 2
      xmethod(3)        3            System.out.print(3 + " ")                1 2 3
     xmethod(4)         4            System.out.print(4 + " ")                1 2 3 4
    xmethod(5)          5            System.out.print(5 + " ")                1 2 3 4 5

You should go through this tutorial( http://www.vogella.com/articles/EclipseDebugging/article.html ) to get the hang of debugging. Debugging a program will help you to get a head-start to resolve queries like this one, yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM