Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Calculate the Factorial of an Integer in C#

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

George Swan
Wales Wales
No Biography provided

Comments and Discussions

GeneralI like this solution. Pinmembermcjohnson4-Oct-11 12:32 
GeneralUpdated to reflect updates to original PinadminChris Maunder4-Oct-11 2:51 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 4 Oct 2011
Article Copyright 2011 by George Swan
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid