Search code examples
c++factorial

Understanding how to use the factorial function in c++


I have this code which works out the factorials for all integers between 0 and 9.

#include <iostream>
using namespace std;

int factorial(int n)
{
    int result = 1;
    if ( n > 0) {
        do {
        result *= n;
        --n;
      } while (n > 1);
    }
    else if ( n < 0) {
       cout << "Error in argument \targument = " <<
        n << "\n";

    }
    return result;
}
    int main()
    {
    for (int i=0 ; i < 10; ++i)
        cout << i << "! = "<< factorial(i) << "\n";
    return 0;

}   

I understand that the "for loop" in the int main section tells us for which integers to work out the factorials for. I understand that the "else if" section tells us that if we input an integer less than 0, we get an error. However I do not understand this part of the code.

        if ( n > 0) {
            do {
            result *= n;
            --n;

What does this part of the code do?

Also why is n being decremented --n;? I am a little confused because the way I see it, if n > 0 and you decrement by saying --n, surely that will mean n < 0 and you will just get an error because of else if?


Solution

  • What does this part of the code do?

    That is the actual calculation of the factorial value (e.g. 4! = 24).

    Also why is n being decremented --n;?

    Because it has to go from the number you want to calculate the factorial for down to zero. For example, "four factorial" (written 4!) means:

    4! = 4 * 3!
     3! = 3 * 2!
      2! = 2 * 1!
       1! = 1 * 0!
        0! = 1     (by definition)
       1! = 1 * 1
      2! = 2 * 1 * 1
     3! = 3 * 2 * 1 * 1
    4! = 4 * 3 * 2 * 1 * 1
       = 24
    

    Therefore, you need to decrement your way down to 0! from n, whatever the value. Notice also that this is a recursive definition.

    I am a little confused because the way I see it, if n > 0 and you decrement by saying --n, surely that will mean n < 0

    Wrong. --n is shorthand for subtracting one, or n = n - 1;. It does not mean negation/opposite of n, or n = -n;.