C++ Program to Find Factorial of a Number
for (int i = 1; i <= n; ++i) result *= i;.Examples
How to Think About It
Algorithm
Code
#include <iostream> using namespace std; int main() { int n; unsigned long long factorial = 1; cout << "Enter a positive integer: "; cin >> n; if (n < 0) { cout << "Factorial is not defined for negative numbers." << endl; return 1; } for (int i = 1; i <= n; ++i) { factorial *= i; } cout << "Factorial of " << n << " is " << factorial << endl; return 0; }
Dry Run
Let's trace the input 5 through the code
Input
User enters n = 5
Initialize factorial
factorial = 1
Loop iteration 1
i = 1, factorial = 1 * 1 = 1
Loop iteration 2
i = 2, factorial = 1 * 2 = 2
Loop iteration 3
i = 3, factorial = 2 * 3 = 6
Loop iteration 4
i = 4, factorial = 6 * 4 = 24
Loop iteration 5
i = 5, factorial = 24 * 5 = 120
End loop
factorial = 120
| i | factorial |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 6 |
| 4 | 24 |
| 5 | 120 |
Why This Works
Step 1: Initialize factorial
We start with factorial = 1 because multiplying by 1 does not change the result and it is the identity for multiplication.
Step 2: Multiply in loop
Each loop step multiplies factorial by the current number i, building the product of all numbers from 1 to n.
Step 3: Final result
After the loop finishes, factorial holds the product of all numbers from 1 to n, which is the factorial.
Alternative Approaches
#include <iostream> using namespace std; unsigned long long factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); } int main() { int n; cout << "Enter a positive integer: "; cin >> n; if (n < 0) { cout << "Factorial is not defined for negative numbers." << endl; return 1; } cout << "Factorial of " << n << " is " << factorial(n) << endl; return 0; }
#include <iostream> using namespace std; int main() { int n; unsigned long long factorial = 1; cout << "Enter a positive integer: "; cin >> n; if (n < 0) { cout << "Factorial is not defined for negative numbers." << endl; return 1; } int i = 1; while (i <= n) { factorial *= i; i++; } cout << "Factorial of " << n << " is " << factorial << endl; return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program multiplies numbers from 1 to n once, so it runs in linear time O(n).
Space Complexity
Only a few variables are used, so space is constant O(1).
Which Approach is Fastest?
The iterative for loop is fastest and safest for large n compared to recursion which can cause stack overflow.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative for loop | O(n) | O(1) | Large inputs, safe and fast |
| Recursive function | O(n) | O(n) | Simple code, small inputs |
| While loop | O(n) | O(1) | Same as for loop, style preference |
unsigned long long to store factorials of larger numbers safely.