Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Question on how this works?

  1. #1
    Junior Member
    Join Date
    Dec 2013
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Question on how this works?

    public static void mystery(int num)
    {
     if (num > 0)
     {
     mystery(num – 1);
     System.out.print(num + " ");
     }
    }
     
    mystery(4);
    System.out.println();

    I was looking through my older notes from a class I took a few years ago, and it was saying the answer was 1 2 3 4 is what outputted when this is run. I would think it is 4 3 2 1, and I don't understand how it is the other way around. Would anyone be kind enough to explain what actually happens to make it 1 2 3 4? Thank you.


  2. #2
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Question on how this works?

    Quote Originally Posted by sammythesp3rmy View Post
    Would anyone be kind enough to explain what actually happens to make it 1 2 3 4? Thank you.
    The print is after the recursive invocation of mystery. The last deepest invocation is with 0 but since there is the condition num>0, no recursion and no print happens. Then gets one step back, where the invocation was with 1 and print it ... and go back where was 2 .....
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

Similar Threads

  1. Replies: 9
    Last Post: September 15th, 2013, 02:48 PM
  2. how this code works?
    By vigneshwaran in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 11th, 2012, 09:18 AM
  3. This Works In My Other Code But Not This One?
    By Ooogel in forum What's Wrong With My Code?
    Replies: 3
    Last Post: October 5th, 2012, 05:49 PM
  4. I have no idea how this works.
    By GeneralPihota in forum Algorithms & Recursion
    Replies: 3
    Last Post: December 29th, 2011, 09:55 PM
  5. GUI Only Works Sometimes
    By bgd223 in forum What's Wrong With My Code?
    Replies: 7
    Last Post: July 12th, 2011, 08:08 AM