In this example, we will calculate the factorial of a number taking the value from the user in C using recursion.
Recursion refers to the function calling itself directly or in a cycle.
Before we begin, you should have the knowledge of following in C Programming:
Factorial of n number: Factorial of n number is the product of all the positive descending integers and is denoted by n!.
Example:
factorial of n (n!) = n * (n-1) * (n-2) * (n-3)….1
factorial of 5 (n!) = 5 * 4 * 3 * 2 * 1
NOTE: Factorial of 0 (0!) = 1
Factorial Program in C using Recursion
/*Find Factorial of a Number using Recursion */
#include <stdio.h>
int factorial_Number(int);
int main()
{
int num, result;
//user input
printf("Enter the Number to Find the Factorial of: ");
scanf("%d", &num);
//Calling function
result = factorial_Number(num);
//Display
printf("Factorial of %d is: %d", num, result);
return 0;
}
int factorial_Number(int n)
{
//Factorial of 0 is 1
if (n == 0)
return (1);
else
return (n* factorial_Number(n - 1)); //recurion: calling function itself
}
Output:
Enter the Number to Find the Factorial of: 5
Factorial of 5 is: 120