C program to find factorial of a given number using recursion
This C program is to find factorial of a given number using recursion.For example, factorial of a given number using recursion, is factorial(5) = 120.
Logic
We include one base case i.e when we have 0, we output the factorial as one and we have finished our program so we need to exit and a non base case i.e. start from n and keep multiplying n with a recursive call by decreasing n by 1.
Dry Run of the Program
Take input as n=4
We enter function fact()
int fact(int n)
n=4
if(n==0) false
else
return (n*fact(n-1)); i.e. return (4*fact(4-1)) i.e. return (4*fact(3))
A recursive call[fact(3)]
if(n==0) false
else
return (n*fact(n-1)); i.e. return (3*fact(3-1)) i.e. return (3*fact(2))
A recursive call[fact(2)]
if(n==0) false
else
return (n*fact(n-1)); i.e. return (2*fact(2-1)) i.e. return (2*fact(1))
A recursive call[fact(1)]
if(n==0) false
else
return (n*fact(n-1)); i.e. return (1*fact(1-1)) i.e. return (1*fact(0))
A recursive call[fact(0)]
if(n==0) true
return 1;
So now we will have
1*1 = 1 … fact(1)
2*1 = 2 …fact(2)
3*2 = 6 …fact(3)
4*6 = 24 …fact(4) ….final answer
Program
#include<stdio.h> int fact(int n) { if(n==0) return 1; else return (n*fact(n-1)); } void main() { int num; printf("Enter the nth term\n"); scanf("%d",&num); printf("Factorial(%d) = %d\n",num,fact(num)); }