I'm currently learning recursion in Java. I have made a little code for practice.
public class Tester{
public static void main(String[] args){
rec(5);
}
public static void rec(int x){
if(x<=0){
return;
}else{
System.out.print(x+" ");
rec(x-1);
}
}
}
// Output: 5 4 3 2 1
But if I now switch System.out.print(x+" ");
with rec(x-1);
, I get a completely different output, namely the reverse: 1 2 3 4 5
How can this be possible? I understand it like that:
We have the integer 5
and we go through the method. The if-statement does not apply, so we decrease 5
by 1
and we have x=4
, we repeat the method (the print is not reached and thus nothing is printed). As said, we do the same with x=4
. If statement does not apply, we decrease 4
by 1
and repeat the method. We repeat till we have that x=0
. In this case, we return, so this is the end of the method. I don't understand at all how we have the reverse output, I don't even understand why we have an output...? :s