2

I was just introduced to recursion and I was given the following lines of code:

public class RecursionThree
{
   public void run(int x )
   {
      if(x<5)
         run(x+1);
      out.println(x);
   }
   public static void main(String args[]  )
   {
      RecursionThree test = new RecursionThree ();
      test.run(1);
   }
}

and the output is supposed to be: 5 4 3 2 1. I get why it would print 5 (because 5<5 would equal false and it would print x, which is 5). However, I do not understand why it prints 4 3 2 1 too. Thanks for your help

5
  • Your output should be 1 2 3 4 5, each on a new line. Recursion as a concept can be seen like having a camera with a detached (live) screen having its lens pointing at its screen, which in turn shows the screen and its image being repeated within the screen of the original image endlessly, except each time smaller. Just like in your case. Your method run() is calling run() again and again, each time giving it a larger number until the condition is met (in this case, until the number is 5). Commented Mar 7, 2016 at 1:26
  • The output is 5 4 3 2 1, each on a new line (I ran the code) but I think I get it now, thank you Commented Mar 7, 2016 at 1:28
  • 2
    @shrmn The output can never be 1 2 3 4 5. Printing is done after the recursion stage, not before. It will be the exact opposite of what you said, i.e. 5 4 3 2 1. Please check before posting. Commented Mar 7, 2016 at 1:30
  • My bad, I interpreted the out.println(x); as being the first thing that happens in the method (before the conditional). Cheers! Commented Mar 7, 2016 at 1:30
  • I understand now! Thank you Commented Mar 7, 2016 at 2:11

2 Answers 2

2

How recursion works is you break down to the base case and build up backwards. In your case. Your base case was x>=5, the point at which it would stop expanding the recursive tree, you can think of the base case as the end of the tree, or leaf. After that it goes back up completing things that were to be done after run was called. SO in your case, each time after calling one, it printed out x.

When x=1, it calls run(2), after run(2) is resolved, it would go to the next line. After run(2), the print out is 5 4 3 2 after that it would print out x coming back to the original call of run(1), which would be 1. This is really great for traversing trees etc and a lot of other problems.

To picture it, when you call run(1)

run(1)
 1<5
  run(2)
   2<5
    run(3)
     3<5
      run(4)
       4<5
        run(5)
          print(5)
       print(4)
     print(3)
   print(2)
 print(1)

As you can see it goes to the base case, and back up.

To get familiar with recursion more, you can do problems like, finding the largest int in an array with the method head being public int findLargest(int [] array, int someNumber) where you would use someNumber to whatever you think you need. Or reversing a string using recursion and one parameter.

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

3 Comments

Thank you so much, this helped a lot
Glad it helped. Do you have any other questions about recursion?
I have new question haha, it would mean a lot if you could take a look at it stackoverflow.com/questions/35835640/recursion-wrong-output
2

For your x=4 case, run(5) was called. After that completed running, control was returned to the callee function, where x is presently 4. So, it executes the line after the if which prints the 4.

The same logic follows for x = 3, 2, 1.

4 Comments

If it says "system.out.println(x)" and x is 5, wouldn't it print 5 and then stop because there's nothing else in "run"? I still don't get why it keeps going back, and I've looked everywhere and I can't get a clear explanation. Does it print "4, 3, 2, 1" because those were the previous values of x and in some way recursion stores those values? Hope you can help me with this and thanks for your help
@JavaB Pretty much. If you note, run(x+1) is called iff x<5. So, for the case where x = 5, run(6) is not called. So, we don't have to worry about that. For x=5 case, after the if condition is checked, 5 is printed. Now, we are done with the function instance for the x=5 case. Time to go back to the x=4 case. The if case has been evaluated. The line after that asks to print 4 to the console. Now, we are done with the function instance for the x=4 case. Now the x=3 case.....
@JavaB Does that answer your question?
@JavaB We never finished executing all the other calls to run--and they have to finish (return/throw) before the closing curly brace.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.