0% found this document useful (0 votes)
5 views6 pages

2 Recursion

Recursion is a programming technique where a function calls itself, known as a recursive function. The document includes a sample C program to calculate the factorial of a number using recursion and discusses limitations such as stack overflow, performance issues, and debugging challenges. It also mentions optimization techniques like memoization and tail recursion to enhance recursive function efficiency.

Uploaded by

ak1908015
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views6 pages

2 Recursion

Recursion is a programming technique where a function calls itself, known as a recursive function. The document includes a sample C program to calculate the factorial of a number using recursion and discusses limitations such as stack overflow, performance issues, and debugging challenges. It also mentions optimization techniques like memoization and tail recursion to enhance recursive function efficiency.

Uploaded by

ak1908015
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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).

You might also like