C# Program to Find Factorial Using Recursion
int Factorial(int n) { if (n <= 1) return 1; else return n * Factorial(n - 1); } which calls itself until it reaches 1.Examples
How to Think About It
if to stop recursion at 1 and else to continue multiplying.Algorithm
Code
using System; class Program { static int Factorial(int n) { if (n <= 1) return 1; return n * Factorial(n - 1); } static void Main() { int number = 5; Console.WriteLine($"Factorial of {number} is {Factorial(number)}"); } }
Dry Run
Let's trace factorial of 5 through the code
Call Factorial(5)
Since 5 > 1, return 5 * Factorial(4)
Call Factorial(4)
Since 4 > 1, return 4 * Factorial(3)
Call Factorial(3)
Since 3 > 1, return 3 * Factorial(2)
Call Factorial(2)
Since 2 > 1, return 2 * Factorial(1)
Call Factorial(1)
Since 1 <= 1, return 1
Return values
Factorial(2) = 2 * 1 = 2 Factorial(3) = 3 * 2 = 6 Factorial(4) = 4 * 6 = 24 Factorial(5) = 5 * 24 = 120
| Call | Return Value |
|---|---|
| Factorial(1) | 1 |
| Factorial(2) | 2 |
| Factorial(3) | 6 |
| Factorial(4) | 24 |
| Factorial(5) | 120 |
Why This Works
Step 1: Base Case
The recursion stops when n is 1 or less, returning 1 to avoid infinite calls.
Step 2: Recursive Call
For values greater than 1, the function calls itself with n-1, building the factorial step by step.
Step 3: Multiplication
Each call multiplies the current number n by the factorial of n-1, combining results as recursion unwinds.
Alternative Approaches
using System; class Program { static int Factorial(int n) { int result = 1; for (int i = 2; i <= n; i++) { result *= i; } return result; } static void Main() { int number = 5; Console.WriteLine($"Factorial of {number} is {Factorial(number)}"); } }
using System; using System.Linq; class Program { static int Factorial(int n) { return n <= 1 ? 1 : Enumerable.Range(1, n).Aggregate((a, b) => a * b); } static void Main() { int number = 5; Console.WriteLine($"Factorial of {number} is {Factorial(number)}"); } }
Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself n times, so the time grows linearly with the input number.
Space Complexity
Each recursive call adds a new layer to the call stack, so space used is proportional to n.
Which Approach is Fastest?
The iterative approach uses constant space and is generally faster for large inputs, while recursion is more elegant but uses more memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive | O(n) | O(n) | Simple code, small inputs |
| Iterative | O(n) | O(1) | Large inputs, performance |
| LINQ Aggregate | O(n) | O(1) | Concise code, readability |