Example:
Input any number: 5
Output: 120
Required knowledge
Basic C programming, Function, RecursionAs 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
Factorial of 10 is 3628800
Happy coding ;)
You may also like
- Function and recursion programming exercises index.
- C program to generate nth Fibonacci term using recursion.
- C program to find GCD (HCF) of any two numbers using recursion.
- C program to find LCM of any two numbers using recursion.
- C program to find sum of all array elements using recursion.
- C program to find reverse of any given number using recursion.
- C program to check palindrome numbers using recursion.
- C program to print all natural numbers using recursion.
- C program to find diameter, circumference and area of a circle using functions.
- C program to find maximum or minimum between two numbers using functions.
- C program to check even or odd numbers using functions.
- C program to print all perfect numbers using functions.