- Asked 3/16
- 2071 Shrawan · 2+2 marks
- 2071 Chaitra · 2 marks
- 2074 Asoj · 2 marks
Recursive function and how it works
Short answer
A recursive function calls itself with a smaller input until a base case stops recursion. It uses stack memory for each call. Example: factorial (n * factorial(n-1)). Use it when a problem decomposes into similar subproblems.
What is a recursive function? How does it work? Give an example of recursive function. When can we use recursive functions?
Recursive function
A recursive function is a function that calls itself, directly or indirectly, to solve a smaller version of the same problem.
How it works
- It must have a base case, a condition that stops the recursion; otherwise it never ends.
- It has a recursive case which calls itself with a smaller (simpler) argument.
- Each call gets its own set of local variables on the stack. When the base case is reached, the calls return one after another in reverse order, and the results are combined.
Example: factorial
#include <stdio.h>
long factorial(int n)
{
if (n <= 1) /* base case */
return 1;
return n * factorial(n - 1); /* recursive case */
}
int main(void)
{
int n = 5;
printf("%d! = %ld\n", n, factorial(n));
return 0;
}
Output:
5! = 120
factorial(3) = 3 * factorial(2)
= 2 * factorial(1)
= 1 <- base case
factorial(2) = 2 * 1 = 2
factorial(3) = 3 * 2 = 6
When to use recursion
When a problem can be divided into similar smaller problems: factorial, Fibonacci series, GCD, power, Tower of Hanoi, binary search, tree traversal and sorting methods like quick sort.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Series (2*3/5)+(4*5/7)+… with functions · Computer Programming, chapter 6
- Function definition; sum of two numbers · Computer Programming, chapter 6
- Reverse a string using functions · Computer Programming, chapter 7 · asked 2×
- Complex number sum via functions · Computer Programming, chapter 8
- Pass student array; display passed students · Computer Programming, chapter 7
- Armstrong number using recursion · Computer Programming, chapter 6
- Normal vs recursive function · Data Structure and Algorithm, chapter 5
- Photoelectric effect: work function of sodium · Electrical Engineering Material, chapter 1 · asked 2×
- Function of painting work · Building Technology, chapter 9
- Is recursion slow; recursive vs non-recursive · Data Structure and Algorithm, chapter 5