Paul Drujco
Paul Drujco

Reputation: 37

Java Recursivity misunderstanding

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

Answers (3)

MC Emperor
MC Emperor

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.

  1. countdown(2) is called
  2. within this method call, n == 2, so else block is executed
  3. countdown(1) is called
  4. within this method call, n == 1, so else block is executed
  5. countdown(0) is called
  6. within this method call, n == 0 thus the if-condition is true, so "Blastoff!" is printed
  7. this method exits, returning to the method denoted by step 3.
  8. n is printed, which has the value 1.
  9. the method exits, returning to the method denoted by step 1.
  10. n is printed, which has the value 2.
  11. the method exits

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

Ben
Ben

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

Tom
Tom

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

Related Questions