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#

3.33/5 (5 votes)
4 Oct 2011CPOL 93.8K  
I looked for a while over the net for a way to easily calculate a factorial value (n!), but nothing was helping and I saw some VERY long and drawn out solutions. Well, it wasn't that hard after I thought about it for a while and this was the easiest solution I could come up with. I hope it helps!

The code below is what I put in my event handler. The comment lists my class variables used.

C#
int Factorial(int input)
{
    int answer = 0;

    if (input > 0)
    {
        count = 1;
        while (count <= input)
        {
            if (count == 1)
            {
                answer= 1;
                count++;
            }
            else
            {
                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)