-3

I am new to Recursion in Java and came across this code in a textbook. After running the code it prints "1 2 3 4 5" and am wondering why it doesn't print "5 4 3 2 1"?

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 + " ");
    }
  }
}
Nikkolash
  • 19
  • 3
  • 4
    Try stepping through it in a debugger. – Thorbjørn Ravn Andersen Jul 15 '19 at 20:10
  • Debugger is a great idea (for this and any future questions you run into). Another thing you could try is to call `System.out.println()` _before_ you call `xMethod(n-1)`. The output should be different. Can you see why it changed? – Kaan Jul 15 '19 at 20:29

3 Answers3

1

This is due to the order of the println() and the recursive call to xMethod()

If you flip the two lines it will print before calling recursively giving you 5 4 3 2 1

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

public static void xMethod(int n) {
    if (n > 0) {
        System.out.print(n + " ");
        xMethod(n - 1);
    }
}
Michael W
  • 3,515
  • 8
  • 39
  • 62
0

Look, before the code System.out.print(n + " "); is called, the method xMethod is called again. BUT the last time the method is called with n = 0, and it doesn't enter the if block.

From this point, the code starts to print the numbers, from the last call towards the first.

Mauricio Sipmann
  • 465
  • 6
  • 21
0

It is just call itself(that's why call it recurring) before print. When it print, n is 1 as it is boundry to exit according to n > 0. So 1, 2, 3, 4, 5.

Qingfei Yuan
  • 1,196
  • 1
  • 8
  • 12