Thread: Recursion

  1. #1
    Registered User
    Join Date
    Jul 2010
    Posts
    1

    Recursion

    Hey. I'm trying to learn C++... not very good at it though, at all. =/

    I'm on lesson 16 and I REALLY just can't seem to get the solution to the challenge they've set...
    Cprogramming.com Tutorial: Recursion
    This is just the beginning of the usefulness of recursion. Heres a little challenge, use recursion to write a program that returns the factorial of any number greater than 0. (Factorial is number*number-1*number-2...*1).
    I really have tried and tried to work it out. But as I said, I'm not good at all, but I really am interested in this sort of stuff & computers.

    Any help please? Thanks.

  2. #2
    Registered User MacNilly's Avatar
    Join Date
    Oct 2005
    Location
    CA, USA
    Posts
    466
    Factorial is:

    !x = 1 if x = 0, else it is x * !(x - 1)

    Any recursive function has to have a "base case" where the recursion stops. For factorial the base case is x=0.

    So you want to write a function fact() that has x as the argument.

    If x = 0, you can just return 1.

    If it is not 0, though, you need to return x * !(x - 1). If only you had a function to computer !(x-1)... you do! It's fact(x-1)...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Template Recursion Pickle
    By SevenThunders in forum C++ Programming
    Replies: 20
    Last Post: 02-05-2009, 09:45 PM
  2. Recursion... why?
    By swgh in forum C++ Programming
    Replies: 4
    Last Post: 06-09-2008, 09:37 AM
  3. Recursion
    By Lionmane in forum C Programming
    Replies: 11
    Last Post: 06-04-2005, 12:00 AM
  4. a simple recursion question
    By tetra in forum C++ Programming
    Replies: 6
    Last Post: 10-27-2002, 10:56 AM
  5. selection sorting using going-down and going-up recursion
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 11-02-2001, 02:29 PM