Recursive Factorial Function


Program Listing

RecursiveFactorial.cpp

/****************************************************************************
*                                                                           *
*   Program:    RecursiveFactorial                                          *
*                                                                           *
*   Purpose:    This program will test the Factorial() function             *
*                                                                           *
****************************************************************************/

//  Header files

#include <iostream>
#include <string>

using namespace std;

//  Functions prototypes

int Factorial(int n);

/****************************************************************************
*                                                                           *
*   Function:   main                                                        *
*                                                                           *
*   Purpose:    To test the Factorial() function                            *
*                                                                           *
****************************************************************************/

int main() {

//  Get a nonnegative integer from the user

    cout << "Enter a nonnegative integer:  " << flush;
    int n;
    cin >> n;
    
//  Find the factorial of the integer and print it

    int fact = Factorial(n);
    cout << "The factorial of " << n << " is " << fact << endl;
    
    return 0;
}

/****************************************************************************
*                                                                           *
*   Function:   Factorial                                                   *
*                                                                           *
*   Purpose:    To computer the factorial of an integer                     *
*                                                                           *
****************************************************************************/

int Factorial(int n) {
    if (n == 0)
        return 1;
    else
        return n * Factorial(n - 1);
}

Sample Run

Enter a nonnegative integer:  8
The factorial of 8 is 40320



Return to Lectures page


e-mail me at robbk@hsc.edu

This page was last modified on Tue Dec 7 16:04:40 1999 .

URL: http://people.hsc.edu/faculty-staff/robbk/Coms261/Examples/RecursiveFactorial.html

Return to Coms 261 home page