Click here to Skip to main content
15,123,367 members
Articles / Programming Languages / C#
Tip/Trick
Posted 3 Oct 2011

Tagged as

Stats

87.8K views
4 bookmarked

Calculate the Factorial of an Integer in C#

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

Share

About the Author


Comments and Discussions

 
QuestionLinq Version Pin
raulito17-Oct-16 6:30
Memberraulito17-Oct-16 6:30 
SuggestionCheck this one Pin
Mathew Sachin24-Dec-14 5:26
MemberMathew Sachin24-Dec-14 5:26 
QuestionFail for higher order numbers Pin
CyberSamuraiii13-May-14 8:21
MemberCyberSamuraiii13-May-14 8:21 
QuestionZero factorial is not undefined Pin
Yitzi916-Aug-13 4:06
MemberYitzi916-Aug-13 4:06 
QuestionSlight Improvement Pin
markbb3322-Feb-13 19:36
Membermarkbb3322-Feb-13 19:36 
GeneralMy vote of 1 Pin
fujiwara129-Oct-12 4:26
Memberfujiwara129-Oct-12 4:26 
GeneralReason for my vote of 1 Really you couldn't find any iterati... Pin
Kerem Kat12-Oct-11 9:55
MemberKerem Kat12-Oct-11 9:55 
GeneralI've reworked the method to make it more generic and cleaner... Pin
Chris Maunder4-Oct-11 3:47
cofounderChris Maunder4-Oct-11 3:47 
GeneralShouldn't the <code>tbxAnswer.Text = total.ToString("n0");</... Pin
George Swan3-Oct-11 21:46
MemberGeorge Swan3-Oct-11 21:46 

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.