Recursion Introduction
Imagine you have a Russian doll. You open it to find a smaller doll, open that to find an even smaller one, and so on until you reach the tiniest doll. Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem.
A recursive function has two parts:
- Base case – condition that stops recursion.
- Recursive case – function calls itself with a smaller input.
Example: Factorial
public static int factorial(int n) {
// base case
if (n <= 1) return 1;
// recursive case
return n * factorial(n - 1);
}
Recursion is natural for problems with a recursive structure, like trees, graphs, and divide-and-conquer algorithms.
Two Minute Drill
- Recursion = function calling itself.
- Base case stops recursion (prevents infinite loops).
- Recursive case reduces problem size each call.
- Recursion uses the call stack; deep recursion may cause stack overflow.
- Many problems (factorial, Fibonacci, tree traversal) are elegantly solved with recursion.
Need more clarification?
Drop us an email at career@quipoinfotech.com
