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
#include <stdio.h> int main() { int n, factorial = 1; printf("Enter a number: "); scanf("%d", &n); for (int i = 1; i <= n; i++) { factorial *= i; } printf("Factorial of %d is %d\n", n, factorial); return 0; }
Dry Run
Let's trace the input 5 through the code
Input
User enters 5, so n = 5
Initialize factorial
factorial = 1
Loop start
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
Loop ends
Loop ends as i > n
Output
Print 'Factorial of 5 is 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 value and it is the identity for multiplication.
Step 2: Multiply in loop
Each loop multiplies factorial by the current number i, building the product step by step.
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 <stdio.h> int factorial(int n) { if (n <= 1) return 1; else return n * factorial(n - 1); } int main() { int n; printf("Enter a number: "); scanf("%d", &n); printf("Factorial of %d is %d\n", n, factorial(n)); return 0; }
#include <stdio.h> int main() { int n, factorial = 1, i = 1; printf("Enter a number: "); scanf("%d", &n); while (i <= n) { factorial *= i; i++; } printf("Factorial of %d is %d\n", n, factorial); return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program runs a single loop from 1 to n, so it takes linear time proportional to n.
Space Complexity
Only a few variables are used, so space is constant regardless of input size.
Which Approach is Fastest?
Both iterative and recursive methods have O(n) time, but iterative uses less memory and is generally faster.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative for loop | O(n) | O(1) | Simple and efficient for all inputs |
| Recursive function | O(n) | O(n) | Clear logic but uses more memory |
| While loop | O(n) | O(1) | Same as for loop, just different syntax |