'Why Recursive method prints numbers backwards [duplicate]
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);
}
}
Solution 1:[1]
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).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
