C program to find factorial of a number using recursion

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

Example:
Input any number: 5
Output: 120

Required knowledge

Basic C programming, Function, Recursion

As I have already explained in my earlier post, what factorial means and how to find factorial of any number using loops. We will be using the basic concept from that program to embed it in our recursive approach.
The factorial of any number can be recursively given by:
fact(0) = 1 {Base case}
fact(num) = num * fact(num-1) {Numbers greater than 1}


Program to find factorial recursively

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

#include <stdio.h>


long long fact(int num);


int main()
{
    int num;
    long long factorial;
    
    /*
     * Reads an integer from user
     */
    printf("Enter any number: ");
    scanf("%d", &num);
    
    factorial = fact(num); //Calls factorial function
    
    printf("Factorial of %d is %lld\n", num, factorial);
    
    return 0;
}



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

Note: The reason why I have used long long is because we know that factorials can grow very rapidly. Hence to store numbers of higher precision I have used long long. Also some compilers doesn't supports long long type so you may replace it with simple long and the format specifier with %ld to overcome the error.

Output
Enter any number: 10
Factorial of 10 is 3628800

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment