A function that calls itself to solve a smaller version of the same problem.
Base Case - When to stop (prevents stack overflow)
Recursive Call - Function calling itself with modified parameters
Processing - Optional work done before or after recursive call
Provides compact approach to problems
Iterative approach generally consumes less time and space
Every recursive call uses stack memory. If base case is not applied, it will consume all the stack memory and the function call stack will overflow
| Type | Description | Processing Location |
|---|---|---|
| Head Recursion | Processing before recursive call | Above recursive call |
| Tail Recursion | Processing after recursive call | Below recursive call |
Logic: sum(n) = n + sum(n-1)
int getSum(int n) {
//base case
if(n == 1)
return 1;
//recursive relation
//sum(n) = sum(n-1) + n;
int ans = getSum(n-1) + n;
return ans;
//processing
}
Logic: fib(n) = fib(n-1) + fib(n-2)