Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Calculate the Factorial of an Integer in C#

4.71/5 (4 votes)
4 Oct 2011CPOL 12.5K  
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;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)