0

Why is recursion backwards when I call the function before printing but not if I print after calling the function?

For some reason I don't understand why the recursive method prints backward when it's the function is being called before the print and why is it not backward when I print before calling the function.

Could someone explain it to me?

public void tricky1(int n) {
    if (n >= 0) {
        System.out.print(n);
        tricky1(n - 2);
     }
}

Second

public void tricky2(int n) {
    if (n >= 0) {
        tricky2(n - 2);
        System.out.print(n);
    }
}
Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
MRSinal
  • 25
  • 1
  • 5
  • Please read: [How to debug small programs (`https://ericlippert.com/`)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Turing85 May 01 '22 at 19:26

1 Answers1

0

When you run this code

tricky2(n - 2);
System.out.print(n);

The result is being printed in ascending order because statement System.out.print(n); is being executed after the very last recursive call in the branch of execution created by the line tricky2(n- 2);.

Conversely, when this snippet is being executed.

System.out.print(n);
tricky2(n - 2);

The number will be printed on the console before the recursive call. Therefore, numbers will get printed in the descending order (from highest to lowest).

Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46