Factorial Computation Program

This is a discussion on Factorial Computation Program within the C++ Programming forums, part of the General Programming Boards category; Ok, so Im trying to write a program that computes factorials recursively. Here is what Ive got (when I asked ...

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    2

    Factorial Computation Program

    Ok, so Im trying to write a program that computes factorials recursively.

    Here is what Ive got (when I asked my teacher for help, he said my factorial.cpp has one key flaw but I cant find it)

    Factorial.cpp

    Code:
    int factorial(int N)
    {
       //cout << "into factorial with " << N << endl;
       if ( N < 1 )
           return 1; // base case
       //cout << " not a base case with N = " << N << endl;
       int answer = factorial(N-1);
       //cout << " returning " << answer << " as answer at N = " << N << endl;
       return answer;
    }

    driveFactorial.cpp
    Code:
    
    #include <iostream>
    #include <fstream>
    using namespace std;
        
    #include "factorial.cpp"
         
    int main()
    {
      int FactForN = 1;
     
      cout << "\n Factorial of what number?  (negative to end) ";
    
      while ( cin >> FactForN && FactForN > 0)
       {
         int answer = factorial(FactForN);
         cout << "\n The factorial of " << FactForN << " is " << answer << endl;
    
         cout << "\n Factorial of what number?  (negative to end) ";
      }
    }

    any help would be appreciated. Thanks!

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    213
    Code:
    if ( N < 1 )
    There is no 0 in factorials. Your base case would be when N = 1.

  3. #3
    Registered User
    Join Date
    May 2008
    Posts
    2
    so I should make it n=1 and not n <1?

  4. #4
    Registered User NeonBlack's Avatar
    Join Date
    Nov 2007
    Posts
    435
    0! is 1 so his base case is correct.

    If we use 0!=1 as our base case then in general,
    N! = N*(N-1)!
    Compare that to what you are doing.

    ALSO, you should include .h files, not .c files
    Last edited by NeonBlack; 05-11-2008 at 07:06 PM.
    I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Factorial program
    By swgh in forum C++ Programming
    Replies: 1
    Last Post: 09-21-2007, 03:01 AM
  2. Using variables in system()
    By Afro in forum C Programming
    Replies: 8
    Last Post: 07-03-2007, 12:27 PM
  3. BOOKKEEPING PROGRAM, need help!
    By yabud in forum C Programming
    Replies: 3
    Last Post: 11-16-2006, 10:17 PM
  4. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21