Can someone please explain to me why this prints out 1 2 3 4 5? I figured it would print out 4 3 2 1 0 but my book and eclipse both say I'm wrong.
public class whatever {
/**
* @param args
*/
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int n){
if (n>0){
xMethod(n-1);
System.out.print(n + " ");
}
}
}
In Java, a method that calls itself is known as a recursive method. And, this process is known as recursion. A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.
A recursive function always has to say when to stop repeating itself. There should always be two parts to a recursive function: the recursive case and the base case. The recursive case is when the function calls itself. The base case is when the function stops calling itself.
Recursion is not hard, whereas thinking recursively might be confusing in some cases. The recursive algorithm has considerable advantages over identical iterative algorithm such as having fewer code lines and reduced use of data structures.
It is pretty simple, these are the calls
main
xMethod(5)
xMethod(4)
xMethod(3)
xMethod(2)
xMethod(1)
xMethod(0)
print 1
print 2
print 3
print 4
print 5
So you see the prints are 1,2,3,4,5
It's the result of the call stack. Here's what it would look like after a call with n = 5
. Rotate your head about 180 degrees, since the bottom of this call chain is actually the top of the stack.
In a recursive call, you have two cases - a base case and a recursive case. The base case here is when n == 0
, and no further recursion occurs.
Now, what happens when we start coming back from those calls? That is, what takes place after the recursive step? We start doing System.out.print()
. Since there's a condition which prevents both recursion and printing when n == 0
, we neither recurse nor print.
So, the reason that you get 1 2 3 4 5
as output is due to the way the calls are being popped from the stack.
It first call itself recursively and only when the recursive call finishes it prints. So think about which call finishes first - it's when n = 0. Then n = 1, etc.
It's a stack and you print after taking from the stack (after the recursion call), so the order is reversed. If you printed before putting on the stack, then the order is preserved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With