Tuesday, June 11, 2013

C++ Program to Calculate Factorial

The factorial of n is the product of all positive integers up to and including N. N! = 1 * 2 *3.. * N. For this program you need to know your data types size and range. Refer to CPlusPlus.com for table that displays size and range of many data types. If you define your variables to be integer data type (integer range is from -2147483648 to 2147483647), the program will give you wrong answer because you will fall out of the range after 13 factorial. You will only get the right answer for the first 12 numbers. To avoid getting wrong answers, you can user double or long double which is basically the same thing which can take up to 15 digits in range.

C Plus Plus Program to Calculate Factorial

#include <iostream>
using namespace std;

int main ()
{
    long double num, count;
    cout<<"Enter a Number to Calculate its Factorial: ";
    cin>>num;
    count = num;
    while (count > 1)
    {
        cout<<count; cout <<" * ";
        num = num * (--count);
        if (count == 1)
            cout<<count <<" = ";
    }
    cout<<num <<endl;
    system("pause");
}

No comments:

Post a Comment