- Write a C program to calculate factorial of a number using recursion.
The factorial of a integer N, denoted by N! is the product of all positive integers less than or equal to n. Factorial does not exist for negative numbers and factorial of 0 is 1.
N! = 1 x 2 x 3 x 4….x (N-2) x (N-1) x N
For Example
5! = 5 * 4 * 3 * 2 * 1 = 120.
We can use recursion to calculate factorial of a number because factorial calculation obeys recursive sub-structure property. Let factorial(N) is a function to calculate and return value of N!. To find factorial(N) we can first calculate factorial(N-1) then multiply it with N.
N! = 1 x 2 x 3 x 4….x (N-2) x (N-1) x N
N! = (N-1)! x N
factorial(N) = factorial(N-1) x N
Function factorial(N) reduces the problem of finding factorial of a number N into sub-problem of finding factorial on N-1. It keeps on reducing the domain of the problem until N becomes zero.
C program to calculate factorial of a number using recursion
Here we are using recursion to calculate factorial of a number. Below program contains a user defined recursive function getFactorial, which takes an integer(N) as input parameter and returns it factorial. To calculate factorial of N, getFactorial function first calls itself to find value of (N-1)! and then multiply it with N to get value of N!. Below c program cannot be used to calculate factorial of very big number because factorial of such numbers exceeds the range of int data type.
/* * C Program to print factorial of a number * using recursion */ #include <stdio.h> #include <conio.h> int getFactorial(int N); int main(){ int N, nFactorial, counter; printf("Enter a number \n"); scanf("%d",&N); printf("Factorial of %d is %d", N, getFactorial(N)); getch(); return 0; } /* * Recursive function to find factorial of a number */ int getFactorial(int N){ /* Exit condition to break recursion */ if(N <= 1){ return 1; } /* N! = N*(N-1)*(N-2)*(N-3)*.....*3*2*1 */ return N * getFactorial(N - 1); }
Program Output
Enter a number 7 Factorial of 7 is 5040
Enter a number 0 Factorial of 0 is 1