C program to find factorial of a number using recursion

Write a recursive function in C to find factorial of a number. How to find factorial of a number using recursion in C program. Logic to find factorial of a number using recursion in C programming.

Example

Input

Input any number: 5

Output

Factorial of 5 = 120

Required knowledge

Basic C programming, If else, Functions, Recursion

Must know – Program to find factorial of a number using loop

Declare recursive function to find factorial of a number

  1. First let us give a meaningful name to our function, say fact().
  2. The factorial function accepts an integer input whose factorial is to be calculated. Hence the function declaration should look like fact(int num);.
  3. The function returns factorial as an integer value. Since, factorial can grow rapidly hence the suitable return type for this function is unsigned long long.

Recursive function declaration to find factorial of a number is – unsigned long long fact(int num);

Logic to find factorial of a number using recursion

Recursive function to find factorial

The above mathematical function defines a recursive approach to find factorial of a number.
Factorial of 0 is 1 which is our base condition i.e. if(num == 0) return 1;. If number is positive then return product of n and factorial of n-1. To find factorial of n-1 we make a recursive function call to our factorial function i.e. num * fact(num - 1);

Program to find factorial using recursion

/**
 * C program to find factorial of any number using recursion
 */

#include <stdio.h>

/* Function declaration */
unsigned long long fact(int num);


int main()
{
    int num;
    unsigned long long factorial;
    
    /* Input an integer from user */
    printf("Enter any number: ");
    scanf("%d", &num);
    
    factorial = fact(num); // Call factorial function
    
    printf("Factorial of %d is %llu", num, factorial);
    
    return 0;
}


/**
 * Function to compute and return factorial of any number recursively. 
 */
unsigned long long fact(int num)
{
    // Base condition
    if(num == 0) 
        return 1;
    else
        return num * fact(num - 1);
}

Note: Some compilers doesn’t support unsigned long long type so you must replace it with unsigned long type and format specifier with %lu, otherwise compiler will report errors.

Output

Enter any number: 10
Factorial of 10 is 3628800

Happy coding 😉