Click here to Skip to main content
11,649,522 members (74,911 online)
Click here to Skip to main content

Tagged as

Calculate the Factorial of an Integer in C#

, 4 Oct 2011 CPOL 4K 1
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...
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)

Share

About the Author

George Swan
Student
Wales Wales
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralI like this solution. Pin
mcjohnson4-Oct-11 12:32
membermcjohnson4-Oct-11 12:32 
GeneralUpdated to reflect updates to original Pin
Chris Maunder4-Oct-11 2:51
adminChris 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 | Terms of Use | Mobile
Web01 | 2.8.150804.4 | Last Updated 4 Oct 2011
Article Copyright 2011 by George Swan
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid