Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
Recursion is a technique in programming where a function calls itself to solve a problem.
Each recursive call works with a smaller part of the original problem until it reaches the base case, where no further calls occur.
Any recursive function must contain two main elements:
Factorial of number n (n!) is the product of all natural numbers from 1 to n.
function factorial(n: number): number {
if (n === 1) return 1; // Base case
return n * factorial(n - 1); // Recursive call
}
console.log(factorial(5)); // 120
Call factorial(5) will unfold like:
factorial(5)
= 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
= 5 * 4 * 3 * 2 * 1
= 120
function printArray(arr: number[], index = 0): void {
if (index >= arr.length) return;
console.log(arr[index]);
printArray(arr, index + 1);
}
printArray([10, 20, 30, 40]);
| Characteristic | Recursion | Iteration |
|---|---|---|
| Approach | Function calls itself | Uses loops |
| Memory | Uses Call Stack | More memory efficient |
| Complexity of understanding | Often harder for beginners | Simpler and more visual |
| Flexibility | Good for recursive structures (trees, graphs) | Excellent for sequential operations |
Be Careful with Stack Overflow:
Recursion can lead to stack overflow if there's no base case or the structure is too deeply nested.