Java Recursion

Discussion in 'School Work Help' started by Flower, Nov 15, 2010.

  1. Flower

    Flower Well-Known Member

    128
    16
    0
    [HIDE]I understand that it will print out 3 *'s but I don't understand how it print 3 +'s.
    After when n=0, should it just print out one +? I'm confused here. Thanks.


    Code:
    [COLOR="Magenta"]public class Stars
    {
    public static void main(String args[])
    {
    Stars.starsAndPlusses(3);
    }
    
    public static void starsAndPlusses(int n)
    {System.out.print(n);
    	if(n==0)
    	{
    		System.out.print("out");
    	}
    	else
    	{
    		System.out.print("one");
    		System.out.print('*');
    		Stars.starsAndPlusses(n - 1);
    		System.out.print("two");
    		System.out.print('+');
    	}
    }
    }[/COLOR]
    The output is:
    3one*2one*1one*0outtwo+two+two+
    [/HIDE]
     
  2. -Tisken-

    -Tisken- Well-Known Member

    hii have you solved the problem yet? :)

    what kind of printout do you want? (cuz i dont really understand the problem)
     
  3. -Tisken-

    -Tisken- Well-Known Member

    yepp after printing those 3* it goes back to the "previous method", cuz it hasnt finished.

    hope you understand my drawing lols
     

    Attached Files:

  4. -Tisken-

    -Tisken- Well-Known Member

    we just had recursion last week haha :D
    was kinda confusing, but now i like it a lot!!
     
  5. nice drawings lol
     
  6. Lol there's nothing hard about writing recursion. Just visualize it.
     
  7. reno

    reno Well-Known Member

    and understand the concept of calling a function/procedure within itself
    =)
     
  8. ^ two comments

    1) while(true) means continue running. Don't think it applies here.
    2) I don't understand your temp stuff. It serves no purpose... You're storying the results of Z,h5(a,b) into temp, and storing temp into a... And in the end, a and b don't do anything...

    The opposite to recursion is iteration.

    This means you need to loop, and you need to have what's called a "sentinel". When you loop, if your condition meets the condition of the sentinel condition, then you break out of the loop. Else, you continue the loop.

    Read the pseudocode (iterative section) of this wiki http://en.wikipedia.org/wiki/Recursion_(computer_science)#Factorial