Factorial Using Recursion (C)¶
π Problem¶
Find the factorial of a number using recursion.
YouTube¶
Wrong Code:
Right Code: Factorial of n:n! = n Γ (n-1) Γ (n-2) Γ ... Γ 1
5! = 5 Γ 4 Γ 3 Γ 2 Γ 1 = 120#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1)
return 1;
return n * factorial(n-1);
}// post decrease // stack overflow
int main() {
int num = 5;
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
Letβs understand how recursion works for n = 5:
factorial(5)
= 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
= 5 * 4 * 3 * 2 * 1
= 120
Base Case
stop recorsion Reduces the problem size Calls function again with smaller valueSocial¶
- GitHub: github.com/lkant8
- LinkedIn: linkedin.com/in/lkant
- YouTube: youtube.com/@alwayslaxmikant
- X: @alwayslaxmikant