C++ Primer Plus Chapter 7 Exercise 5

c plus plusTo understand recursion, one must understand recursion.

Define a recursive function that takes an integer argument and returns the factorial of that argument. Recall that 3 factorial, written 3!, equals 3 × 2!, and so on, with 0! defined as 1. In general, if n is greater than zero, n! = n * (n – 1)!. Test your function in a program that uses a loop to allow the user to enter various values for which the program reports the factorial.

#include <iostream>

using namespace std;

int factorial(int number);

int main()
{
    int number;
    while(number != -1)
    {
        cout << "Enter a number to find it's factorial (q to quit): ";
        cin >> number;
        if(!cin.good())
            break;
        else
        {
            int factor;
            factor = factorial(number);
            cout << "Factorial " << number << " is " << factor << endl;
        }
    }
    return 0;
}

int factorial(int number)
{
    if(number == 0)
        return 1;
    return number * factorial(number - 1);
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s