C# Program to Find Factorial of a Number
for (int i = 1; i <= n; i++) factorial *= i;.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { Console.Write("Enter a number: "); int n = int.Parse(Console.ReadLine()); long factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; } Console.WriteLine($"Factorial of {n} is {factorial}"); } }
Dry Run
Let's trace the input 5 through the code
Input
User enters 5
Initialize factorial
factorial = 1
Loop i=1
factorial = 1 * 1 = 1
Loop i=2
factorial = 1 * 2 = 2
Loop i=3
factorial = 2 * 3 = 6
Loop i=4
factorial = 6 * 4 = 24
Loop i=5
factorial = 24 * 5 = 120
End loop
Print factorial = 120
| i | factorial |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 6 |
| 4 | 24 |
| 5 | 120 |
Why This Works
Step 1: Start with 1
We start factorial at 1 because multiplying by 1 keeps the value unchanged and is the base for multiplication.
Step 2: Multiply in loop
Each loop step multiplies the current factorial by the next number using factorial *= i to build the product.
Step 3: Result after loop
After the loop finishes, factorial holds the product of all numbers from 1 to n, which is the factorial.
Alternative Approaches
using System; class Program { static long Factorial(int n) { if (n <= 1) return 1; return n * Factorial(n - 1); } static void Main() { Console.Write("Enter a number: "); int n = int.Parse(Console.ReadLine()); Console.WriteLine($"Factorial of {n} is {Factorial(n)}"); } }
using System; using System.Linq; class Program { static void Main() { Console.Write("Enter a number: "); int n = int.Parse(Console.ReadLine()); long factorial = n == 0 ? 1 : Enumerable.Range(1, n).Aggregate((a, b) => a * b); Console.WriteLine($"Factorial of {n} is {factorial}"); } }
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs from 1 to n, so the time grows linearly with n, making it O(n).
Space Complexity
Only a few variables are used, so space is constant O(1).
Which Approach is Fastest?
The iterative loop is fastest and safest; recursion adds overhead and risk of stack overflow; LINQ is concise but slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative loop | O(n) | O(1) | General use, large inputs |
| Recursive method | O(n) | O(n) | Simple code, small inputs |
| LINQ Aggregate | O(n) | O(1) | Concise code, readability |