Recursion
What is Recursion?
• What is recursive function?
Ans.
A function which calls itself is called recursive
function and this technique is known as
recursion.
Syntax
LIFO
Syntax:
M1()
void main()
{
....
m1() M1()
......
}
M1()
Void m1()
{ Main()
.....
m1() //recursive function
...... STACK
}
Write a program to calculate factorial of a number using recursive function?
#include <stdio.h>
// Recursive function to calculate factorial
int factorial(int n) {
if (n == 0) // Base case: factorial of 0 is 1
return 1;
else
return n * factorial(n - 1); // Recursive case
}
int main() {
int num;
// Input from user
printf("Enter a positive integer: ");
scanf("%d", &num);
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
// Call the recursive function
printf("Factorial of %d is %d\n", num, factorial(num));
}
return 0;
}
Limitations of Recursion
Stack Overflow: Too many recursive calls can cause memory overflow.
Performance Issues: Recursion can be slower due to overhead from function calls.
Difficult Debugging: Tracing recursive calls can be tricky.
Optimizing Recursive Functions
• Memoization: Store results of sub-problems to avoid
repeated computation.
• Tail Recursion: Use tail recursion to optimize
memory usage (some languages).