View Single Post
Old Jul 26th, 2007, 10:18 AM   #2
Infinite Recursion
Programming Guru
 
Infinite Recursion's Avatar
 
Join Date: Jul 2004
Location: United States
Posts: 3,467
Rep Power: 8 Infinite Recursion is on a distinguished road
Send a message via MSN to Infinite Recursion Send a message via Yahoo to Infinite Recursion
Follow your books suggestion, so you can see the logic in the recursion.

int factorial(int number)
{
   if (number <= 1)

      return 1;

   else
   {
      std::cout << number << " * " << "factorial(" << number << " - 1)" << std::endl;
      return number * factorial(number - 1);
   }
}

The flow will be:

4 * factorial(4 - 1)
3 * factorial(3 - 1)
2 * factorial(2 - 1)
Answer: 24


Mathematically the factorial of 4, would equate to:

4 × 3 × 2 × 1 = 24

Do you see the pattern?
__________________
http://jasonpowers.net

"There are a thousand hacking at the branches of evil to one who is striking at the root."
Infinite Recursion is offline   Reply With Quote