Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem. It’s elegant but tricky for beginners—let’s break it down with clear examples in Python, JavaScript, and Java.
You’re Not a Senior Developer Until You Have These 8 Traits
Recursion solves problems by:
See document.querySelector() vs. getElementById(): Which is Faster?
def factorial(n):
if n == 1: # Base case
return 1
return n * factorial(n - 1) # Recursive case
print(factorial(5)) # Output: 120 function factorial(n) {
if (n === 1) return 1; // Base case
return n * factorial(n - 1); // Recursive case
}
console.log(factorial(5)); // Output: 120 public class Main {
static int factorial(int n) {
if (n == 1) return 1; // Base case
return n * factorial(n - 1); // Recursive case
}
public static void main(String[] args) {
System.out.println(factorial(5)); // Output: 120
}
} def fibonacci(n):
if n <= 1: return n # Base case
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(6)) # Output: 8 javascript
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(6)); // Output: 8 public class Main {
static int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String[] args) {
System.out.println(fibonacci(6)); // Output: 8
}
} ✔ Tree/Graph Traversal (e.g., binary search trees).
✔ Divide & Conquer Algorithms (e.g., mergesort).
✔ Problems with repetitive subproblems (but watch for inefficiency!).
❌ Missing base case → Stack Overflow!
❌ Exponential time complexity (e.g., naive Fibonacci).
Try implementing a recursive sum of numbers from 1 to n in all three languages!
Latest tech news and coding tips.
The Geolocation API allows a web application to access a user’s geographical location (latitude, longitude, and more), with…
1. What Is the Golden Ratio? The Golden Ratio, represented by the Greek letter φ (phi), is…
In CSS, combinators define relationships between selectors. Instead of selecting elements individually, combinators allow you to target elements based…
Below is a comprehensive, beginner-friendly, yet deeply detailed guide to Boolean Algebra, complete with definitions, laws,…
Debugging your own code is hard enough — debugging someone else’s code is a whole…
Git is a free, open-source distributed version control system created by Linus Torvalds.It helps developers: Learn how to…