0
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?

2
  • 3
    It would really help if you'd format your code. It's very hard to read while it's completely unindented. Commented Sep 10, 2014 at 15:51
  • That is clearly not the actual output of this program. Commented Sep 10, 2014 at 16:44

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

You just formatted the code and that is the answer :) +1.
@sᴜʀᴇsʜᴀᴛᴛᴀ the rich get richer
@jon skeet: But why would it return back to call printnum(3)? I know that the last 321 and were from the after recursion statement but I don't understand that where exactly and why the value decremented?
@GurupratapSaini: It's not that the value was decremented - it's that the recursive call returns to the caller, that's all. It's a normal method call - it's not like the recursive call "replaces" the current call.
1

If you expect it to end at 3 then please remove the second

System.out.println( a);

The out put you see is correct and not unexpected as when it is greater than 3 the it return the stack call and prints in in the reverse order.

Comments

0

What you getting as output is correct according to your code. You get extra lines due to the your second System.out.println("After recursion: " + a);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.