0

I want to take an integer n from the user and use it to print n-0, n-1, n-2, and so on down to zero (one number per line) and then back from from 0! to n!. Recursively. But I'm pretty much totally lost as my understanding of recursion is shoddy at best (being generous). Here's my meager code thus far:

static void p(int n)
{
    if (n == 0)
    {
        System.out.println(n);
    }
    else
    {
        System.out.println(n);
        p(n-1);
    }
}

Thanks for reading!

8
  • 3
    Being at total loss for lack of understanding doesn't imply that others should do your homework.
    – devnull
    Feb 27, 2014 at 19:41
  • Of course not. But a nudge in the right direction would be nice.
    – CSpadawan
    Feb 27, 2014 at 19:42
  • Fun, your almost there. Remember recursion is like a stack, when you make the call to p(n-1) your method pauses their and goes to the next one. When n=0 you break that recursion and start to come back out of that stack going backward. You just need 1 more line of code to finish it!
    – ug_
    Feb 27, 2014 at 19:43
  • also you should read a java book first.
    – Luis Pena
    Feb 27, 2014 at 19:43
  • Your function boil down to: System.out.println(n); if (n!=0) p(n-1);. Now ask yourself, is that you wanted. Does that show any bit of effort?
    – devnull
    Feb 27, 2014 at 19:45

1 Answer 1

2

didn't test it, but this should work.

static void p(int n)
{

    System.out.println(n);
    if (n > 0)
    {
        p(n-1);
    }
    System.out.println(n);

}

I'd recommend you to debug through the code to understandy, why this code works

UPDATE:

static int p(int n)
   {

    System.out.println(n);
    int newN = n;
    if (n > 0)
    {
        newN = n*p(n-1);
    }
    System.out.println(newN);
    return newN==0?1:newN;
}
13
  • 1
    Why a second println? That will produce unnecessary output.
    – BVB
    Feb 27, 2014 at 19:49
  • You don't need the final println call there.
    – JamesB
    Feb 27, 2014 at 19:52
  • @BVB, JamesB: the second println is the second part of the question. CSpadawan wanted to count down and then up. Feb 27, 2014 at 20:01
  • I wanted to print back up but with factorials. So 0! to n!. Normally I'd calculate them by returning n*p(n-1) but I'm not sure how to do that with void here.
    – CSpadawan
    Feb 27, 2014 at 20:02
  • 1
    @CSpadawan this a inline if-else. if the condition (newN==0) is true, it returns 1, else newN Feb 27, 2014 at 20:32

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.