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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | /*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