Calculate the Factorial of an Integer in C#






4.71/5 (4 votes)
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; }