Factorial program in C using recursion
In this post, you will learn how to write a factorial program in C using recursion.
The factorial is normally used in different areas of mathematics, including algebra, mathematical analysis, and combinations and permutations. The factorial of a number n is denoted by n!. This is the product of all positive numbers less than or equal to n. It is calculated as -
n! = n X (n-1) X (n-3) X ……… X 3 X 2 X 1
An example of factorial
Suppose we want to get a factorial of 7, then the factorial will be-
7! = 7 X 6 X 5 X 4 X 3 X 2 X 1
5040
Factorial program in C using recursion
Here is the C program to find the factorial of a number using the recursion function. A recursion function is a function that is called by itself. If the number is equal to the 0, it returns 1. The factorial of a number less than equals to 0 does not exist. If the number is greater than 1, the function calls recursively and finds the factorial of a number.
The given C program takes an int as an argument and stores it in the variable num. For finding the factorial of number 8, a recursive function find_factorial() is called with argument 8. The number is not equal to 0, so if the condition becomes true, the recursive function is called again with the number 7. This continues until the number becomes 0. Finally, the recursive function will return 8*7*6*5*4*3*2*1*1 to the main function.
#include<stdio.h>
// recursive function
// to find factorial of a number
int find_factorial(int num)
{
if(num!=0)
return num*find_factorial(num-1); // general case
else
return 1; // base case
}
int main()
{
int num, result;
// user input
printf("Enter a positive number: ");
scanf("%d",&num);
// call recursion function
result= find_factorial(num);
// display result
printf("Result = %d\n",result);
return 0;
}
Output of the above code:
Enter a positive number: 8
Result = 40320
Enter a positive number: 10
Result = 3628800
Related Articles
Prime factors of a number in cArmstrong number program in c
Write a program to check leap year in c
C program to find area of rectangle
C program to convert celsius to fahrenheit
Fibonacci series program in C using recursion
Write a program to find area of circle in C
C program to find greatest of three numbers
C program for addition of two numbers
C program to calculate compound interest
C program to find the ASCII value of a character
C program to convert Decimal to Octal
C program to convert decimal to binary
Write a C program to calculate Simple Interest
C program to check whether a number is even or odd
C program to reverse a number
C program to check palindrome number
C program to check whether an alphabet is a vowel or consonant
Program to find square root of a number in C
C program to check whether a number is positive or negative