Click here to Skip to main content
12,946,164 members (53,834 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


4 bookmarked
Posted 3 Oct 2011

Calculate the Factorial of an Integer in C#

, 4 Oct 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

int Factorial(int input)
    int answer = 0;
    if (input > 0)
        count = 1;
        while (count <= input)
            if (count == 1)
                answer= 1;
                answer = count * answer;
        MessageBox.Show("Please enter only a positive integer.");
    return answer;


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


About the Author

You may also be interested in...

Comments and Discussions

QuestionLinq Version Pin
raulito17-Oct-16 5:30
memberraulito17-Oct-16 5:30 
SuggestionCheck this one Pin
Member 1096039624-Dec-14 4:26
memberMember 1096039624-Dec-14 4:26 
QuestionFail for higher order numbers Pin
CyberSamuraiii13-May-14 7:21
memberCyberSamuraiii13-May-14 7:21 
QuestionZero factorial is not undefined Pin
Member 806338616-Aug-13 3:06
memberMember 806338616-Aug-13 3:06 
QuestionSlight Improvement Pin
markbb3322-Feb-13 18:36
membermarkbb3322-Feb-13 18:36 
GeneralMy vote of 1 Pin
fujiwara129-Oct-12 3:26
memberfujiwara129-Oct-12 3:26 
GeneralReason for my vote of 1 Really you couldn't find any iterati... Pin
Kerem Kat12-Oct-11 8:55
memberKerem Kat12-Oct-11 8:55 
GeneralI've reworked the method to make it more generic and cleaner... Pin
Chris Maunder4-Oct-11 2:47
adminChris Maunder4-Oct-11 2:47 
GeneralShouldn't the <code>tbxAnswer.Text = total.ToString("n0");</... Pin
George Swan3-Oct-11 20:46
memberGeorge Swan3-Oct-11 20: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170518.1 | Last Updated 4 Oct 2011
Article Copyright 2011 by mcjohnson
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid