Search code examples
c++functionrecursionfactorial

recursive function that returns factorial C++


I am trying to solve at the following exercise from the C++ Primer Plus book.

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.

I wrote the code that goes into main().

#include <iostream>
using namespace std;

int factorial(int n);


int main()
{
    int number= 0;
    cout<<"Enter a number(0 to quit): ";
    while (cin >> number && number! = 0)
    {
        cout<< "Here is the factorial of the number: "<< factorial (number) << ". \n"
        "Enter next number(0 to quit): ";
    }


    return 0;
}

Now I can't think of a proper recursive function declaration. Can someone help by writing the easiest (for someone new in programming) to grasp function declaration for this exercise?


Solution

  • When designing a recursive algorithm to calculate the factorial of any number, we must first identify the base case, which is the part of the calculation that we can solve without recursion. That is the case where n = 0 then factorial(n) = 1.

    This tells how to solve the problem when nis equal to 0, but what do we do when n is greater than 0? That is the recursive case, or the part of the problem that we use recursion to solve. If n > 0, then factorial(n) = n * factorial(n-1). This states that if n is greater than 0, the factorial of n is n times the factorial of n-1.

    int factorial(int n)
    {
        if (n == 0)
            return 1; // base case
        else
            return n * factorial(n-1); // recursive case
    }