C Program to Find Factorial of a Number using Recursion

Here is 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.

#include <stdio.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));
    
    return 0;
}

int getFactorial(int N){
    /* Exit condition to break recursion */
    if(N <= 1){
         return 1;
    }  
    return N * getFactorial(N - 1);
}
Output
Enter a number 
7
Factorial of 7 is 5040
Enter a number 
0
Factorial of 0 is 1

Related Topics
C Program to calculate factorial of a number
C program for palindrome check using recursion
C program to find power of a number using recursion
C program to check armstrong number
C program to print fibonacci series using recursion
C program to reverse a string using recursion
C program to find sum of array elements using recursion
C program to insert an element in an array
List of all C Programs