user122144
user122144

Reputation:

How does changing were the recursive function is called change the result?

I am reading a book called "Think Java: How to think like a Computer Scientist", and I recently covered recursive methods.

public static void countdown(int n)
    if (n == 0) {
        System.out.println("Blastoff!");
    } else {
        System.out.println(n);
        countdown(n - 1);
    }
}

This would be a normal recursive method used to count down to 0 and I understand what is happening, but if you make the recursive call before the System.out.println like this

if (n == 0) {
    System.out.println("Blastoff!");
} else {
    countup(n - 1);
    System.out.println(n);
}

it counts the oppisote way, so If I gave the argument 3 for both of these condital statements the 1st one goes "3, 2, 1, Blastoff!" but the 2nd 1 goes "Blastoff, 1 ,2 ,3".... I don't understand how this works, can someone try to explain what is happening in this code that makes it count in the opposite way?

Upvotes: 2

Views: 167

Answers (2)

user4398985
user4398985

Reputation:

if (n == 0) {
    System.out.println("Blastoff!");
} else {
    countup(n - 1);
    System.out.println(n);
}

Thats just because you are placing countdown(n-1) before the system.out.println(n);

When you place before the System.out.println(n), the method will keep calling from countdown(n-1) till it ends the call and the cursor goes to next system.out.println.

So, that's how a recursion works, its like a self contained method, one method calling another method......finally onces the last method gets finished, its comes back to last-1 and then last-2 and the last-n

In your case, first it goes to countdown(n-1), and keep caling the same method till it reachs, n==0. Once n==0, then all the method calls get back to their System.out.println(n);

Upvotes: 1

Shahid
Shahid

Reputation: 2330

When you call countup(n - 1) before print, the print is not reachable until recursion stops. During recursion, numbers are pushed into stack. After recursion has been completed, the all numbers are popped out from stack.

We know, stack is LIFO (Last In First Out). Since it push into the stack in order 3,2,1. That's why when the numbers are popped out from stack, they are in order 1, 2, 3.

But in the first approach, print is done before recursive call. That's why you are getting in order 3,2,1.

Upvotes: 0

Related Questions