'In this example of recursion, how come the second printline prints the second half of the output?
I understand how calling the recursion method (n-1) prints out 4 3 2 1, and since on the last one, n=0; it breaks out of the loop I think, however, my lack of understanding comes from how the second print line prints 1 2 3 4.
static void recursion(int n) {
if(n>0) {
System.out.println(n);
recursion(n-1);
System.out.println(n);
}
}
public static void main(String[] args) {
recursion(4);
}
}
output: 4 3 2 1 1 2 3 4
Solution 1:[1]
You call recursion(4)
which prints 4
then calls recursion(3)
which prints 3
then calls recursion(2)
which prints 2
then calls recursion(1)
which prints 1
then calls recursion(0)
which does nothing
and returns to the previous level
which prints 1
and returns to the previous level
which prints 2
and returns to the previous level
which prints 3
and returns to the previous level
which prints 4
and returns to the previous level
and we're done
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 | dangling else |
