In this guide, we will write a C Program to find factorial of a number using recursion. Recursion is a process in which a function calls itself in order to solve smaller instances of the same problem. This process continues until the smaller instance reaches a base case, at this post the recursion process stops and produces the result.
Key Concepts of recursion process
- Base Case: This is the condition at which the recursion process stops. Without a base case, the function would call itself indefinitely, leading to a stack overflow.
- Recursive Case: This part of the function calls itself with a modified argument, moving towards the base case.
C Program to find factorial of a number using recursion
The explanation of the program is available at the end of this code. The brief explanation of important lines is provided in the program itself using comments.
#include <stdio.h>
// A recursive function to calculate factorial
int factorial(int n) {
if (n == 0) {
return 1; // Base case
} else {
//function calling itself with modified argument
return n * factorial(n - 1);
}
}
int main() {
int num;
// Prompt user to enter a number
printf("Enter a non-negative integer: ");
scanf("%d", &num); //store the number in num
// Validate the input. Check whether the entered
// number is non-negative.
if (num < 0) {
printf("Factorial is calculated for negative numbers.\n");
} else {
// Calculate and print the factorial for input number
printf("Factorial of %d is %d\n", num, factorial(num));
}
return 0;
}
How Recursion Works in Factorial Example:
Base Case:
if (n == 0) {
return 1;
}
When n is 0, the function returns 1, stopping further recursive function calls.
Recursive Case:
return n * factorial(n - 1);
For a positive integer n, the function calls itself with the argument n - 1 and multiplies the result by n.
Example Output:
Let’s say we call factorial(4):
factorial(4)callsfactorial(3)factorial(3)callsfactorial(2).factorial(2)callsfactorial(1).factorial(1)callsfactorial(0).factorial(0)returns1(base case).factorial(1)returns1 * 1 = 1.factorial(2)= 2 * factorial(1) = 2*1 = 2factorial(3)= 3 * factorial(2) = 3*2 = 6factorial(4)= 4 * factorial(3) = 4*6 = 24
Leave a Reply