Click here to Skip to main content
15,882,017 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Calculate the Factorial of an Integer in C#

Rate me:
Please Sign up or sign in to vote.
4.71/5 (4 votes)
4 Oct 2011CPOL 12K   1   2
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)


Written By
Student
Wales Wales
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralI like this solution. Pin
mcjohnson4-Oct-11 12:32
mcjohnson4-Oct-11 12:32 
GeneralUpdated to reflect updates to original Pin
Chris Maunder4-Oct-11 2:51
cofounderChris Maunder4-Oct-11 2:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.