public class testing
{
public static void printnum(int a)
{
System.out.println( a);
if(a <= 3)
{
System.out.println("recursed");
printnum(a+1);
}
System.out.println( a);
}
public static void main(String...s)
{
printnum(1);
}
}
output:
1
2
3
3
2
1
I expected the program to end at last 3 but I do not understand where are the next '2' and '1' coming from? How and why is it decrementing?
You've got two calls to System.out.println(a)
. You'll find it much easier to understand if you differentiate between them:
public static void printNum(int a)
{
System.out.println("Before recursion: " + a);
if(a <= 3)
{
System.out.println("Recursing");
printNum(a + 1);
}
System.out.println("After recursion: " + a);
}
Basically, your calls nest - your most deeply nested call will print:
Before recursion: 4
After recursion: 4
... and then it will return back to the call to printNum(3)
, which will print:
After recursion: 3
and return to the call to printNum(2)
, which will print
After recursion: 2
etc.
Now would also be a good time to learn how to use a debugger to step through your code, look at the stack at every point, etc.
See more on this question at Stackoverflow