65.9K
CodeProject is changing. Read more.
Home

Calculate the Factorial of an Integer in C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.71/5 (4 votes)

Oct 4, 2011

CPOL
viewsIcon

12511

Recursion is a neat way of calculating a number's factorial but there is a danger of the stack overflowing when the number is large. The following is a simplified version of the original. It obviates the need for the if else statements within the where loop.int Factorial(int input){ int...

Recursion is a neat way of calculating a number's factorial but there is a danger of the stack overflowing when the number is large. The following is a simplified version of the original. It obviates the need for the if else statements within the where loop.
int Factorial(int input)
{
    int answer = 0;
    if (input > 0)
    {
        int count = input;
        int answer = 1;
        while (count > 1)
        {
            answer = count * answer;
            count--;
        }
    }
    else
    {
        MessageBox.Show("Please enter only a positive integer.");
    }

    return answer;
}