Understanding Factorial Program in C#: With Code Examples
Learn how to calculate factorial in C# using loops and recursion, with clear code examples and explanations for beginners.
What is a Factorial?
The factorial of a number is the product of all positive integers from 1 up to that number, commonly denoted with an exclamation mark, such as 5! = 5 x 4 x 3 x 2 x 1. It's a fundamental mathematical concept frequently used to teach loops and recursion.
Factorial Using a For Loop
The most straightforward way to calculate a factorial in C# is with a for loop that multiplies a running total by each number from 1 up to the input value, making it easy to trace and understand step by step.
Factorial Using Recursion
A recursive factorial method calls itself with a smaller value each time until it reaches the base case of 0 or 1, elegantly expressing the mathematical definition directly in code.
Handling Edge Cases
Well-written factorial programs should handle edge cases like zero (which returns 1) and negative numbers (which are undefined), along with considering overflow for very large inputs using types like long or BigInteger.
Loop and Recursive Versions in Code
Both approaches below return the same result. The return type is long because factorials grow very quickly.
static long FactorialLoop(int n)
{
if (n < 0) throw new ArgumentOutOfRangeException(nameof(n), "n must be 0 or more");
long result = 1;
for (int i = 2; i <= n; i++)
{
result *= i;
}
return result;
}
static long FactorialRecursive(int n)
{
if (n < 0) throw new ArgumentOutOfRangeException(nameof(n), "n must be 0 or more");
if (n <= 1) return 1; // base case
return n * FactorialRecursive(n - 1); // recursive case
}
Console.Write("Enter a number: ");
if (int.TryParse(Console.ReadLine(), out int num) && num >= 0)
Console.WriteLine($"{num}! = {FactorialLoop(num)}");
else
Console.WriteLine("Please enter a whole number of 0 or more.");
The loop starts at 2 because multiplying by 1 changes nothing. Using int.TryParse instead of int.Parse means a typo such as "abc" prints a friendly message rather than crashing the program.
Tracing 5! Through the Recursion
Recursion can feel like magic until you follow the calls. Each call waits for the one below it to finish:
FactorialRecursive(5) = 5 * FactorialRecursive(4)
FactorialRecursive(4) = 4 * FactorialRecursive(3)
FactorialRecursive(3) = 3 * FactorialRecursive(2)
FactorialRecursive(2) = 2 * FactorialRecursive(1)
FactorialRecursive(1) = 1 <- base case reached
Unwinding: 2 * 1 = 2, 3 * 2 = 6, 4 * 6 = 24, 5 * 24 = 120
Every pending call sits on the call stack. For small inputs that is fine, but extremely deep recursion can exhaust the stack and crash with a StackOverflowException, which C# cannot catch. The loop version uses constant memory, so it is the safer default in production code.
Overflow Limits and BigInteger
Factorials outgrow standard number types fast. An int holds results only up to 12!, and a long holds results up to 20!. By default, C# does not warn you when a calculation overflows; the value silently wraps around and you get a wrong, sometimes negative, answer.
You have two good options. Wrap the multiplication in a checked block so overflow throws an OverflowException, or switch to System.Numerics.BigInteger, which grows as large as memory allows:
using System.Numerics;
static BigInteger FactorialBig(int n)
{
BigInteger result = BigInteger.One;
for (int i = 2; i <= n; i++)
result *= i;
return result;
}
Console.WriteLine(FactorialBig(30)); // 265252859812191058636308480000000
// Overflow detection with long
long Safe(int n) { long r = 1; checked { for (int i = 2; i <= n; i++) r *= i; } return r; }
For a compact one-liner, LINQ also works: Enumerable.Range(1, n).Aggregate(1L, (acc, x) => acc * x). It returns 1 for zero because the range is empty and the seed is 1.
Which version should you pick? In an interview, show the recursive one to prove you understand base cases, then mention the loop as the practical choice. In real code, use the loop with long when inputs are guaranteed small, and BigInteger when users can enter any size. Combinatorics problems, such as counting arrangements or computing nCr, are where factorials appear most often in practice, and there you can often cancel terms instead of computing full factorials at all.
Mistakes Seen in Beginner Factorial Programs
- Starting the result at 0. Anything multiplied by zero stays zero, so every answer becomes 0.
- Missing the base case. A recursive method without
if (n <= 1) return 1;calls itself forever. - Using
intfor the result. Inputs above 12 quietly produce garbage values. - Not rejecting negative input. Factorial is undefined for negatives; fail clearly instead of returning 1.
- Recomputing in a loop. If you need many factorials, build them incrementally or cache them rather than recalculating each from scratch.