C Program to Calculate Factorial of a given Number using Recursion.
Objective
Write a C program to calculate the factorial of a number using Recursion.
Algorithm / Approach
- In the
fact(int x)function, define a Base Case:if (x == 0 || x == 1) return 1;. - Define the Recursive Case:
else return x * fact(x - 1);. - When
fact(5)is called, it returns5 * fact(4), which triggers another call, continuing until it hits the base case of 1.
main.c
#include<stdio.h>
int fact(int);
int main(){
int n,res;
printf("Enter number: ");
scanf("%d",&n);
res = fact(n);
printf("Factorial : %d",res);
return 0;
}
int fact(int x){
if(x==0 || x==1){
return 1;
}
else{
return x*fact(x-1);
}
}
Expected Output
Enter a Number : 5 Factorial = 120
Explanation of the Program
- Recursion is an advanced programming technique where a function calls ITSELF to solve a smaller piece of the original problem.
- Every recursive function must have a "Base Case"—a condition where it stops calling itself. If you forget the base case, the function will infinitely loop until the computer runs out of memory (Stack Overflow).
Complexity
Time Complexity
O(n) - N recursive calls.
Space Complexity
O(n) - Because every recursive call consumes space on the Call Stack.