Reputation: 37
I'm not understanding this code, why it counts up. If I change the order in the print statement with recursivity call It makes sense to me, but as it is why it is counting up. In by book it says that "System.out.println happens just before each recursive call returns. As a result, it counts up instead of down." And I am not understanding It. Appreciate your help.
public static void countdown(int n)
{
if (n == 0)
{
System.out.println("Blastoff!");
}
else
{
countdown(n - 1);
System.out.println(n);
}
}
Upvotes: 0
Views: 94
Reputation: 23017
countdown(n - 1);
System.out.println(n);
It indeed counts up.
Let's take a look at what actually happens: Each countdown
call first calls itself, even before anything is written to System.out
.
In the following example, let's say I call countdown
with 2
as argument.
countdown(2)
is calledn == 2
, so else
block is executedcountdown(1)
is calledn == 1
, so else
block is executedcountdown(0)
is calledn == 0
thus the if-condition is true, so "Blastoff!" is printedn
is printed, which has the value 1.n
is printed, which has the value 2.Note that each method call has its own local variables, like n
. So the output is:
Blastoff!
1
2
as expected. You see that, just according to what the book says, the method calls itself prior to printing something to sysout.
Upvotes: 1
Reputation: 54
you should change the condition 'n == 0' to 'n <=0'. because if you pass negative value then it wont stop and you might see negative number.
lets says if you passed n = -3. then it would keep printing -3, -4...etc.
Upvotes: 1
Reputation: 224
So, if n != 0, your program running code in "else" block, where is another call to method countdown(n-1). For example, if you put n = 3, this code will be running as long as n > 0. So, basiclly running method run herself, looks like this:
countdown(3) call method countdown(2), and then countdown(2) call countdown(1). It will happen as long as n will be higher than 0. If n == 0, it will print Your message.
Upvotes: 2