Recursive Functions in Java
✅ Recursive Functions in Java
A recursive function is a method that calls itself to solve a problem.
🔹 Key Concepts
-
Base Case – condition to stop recursion
-
Recursive Case – where the method calls itself
🔁 Recursion breaks the problem into smaller subproblems until the base case is reached.
🔸 Example 1: Factorial of a Number
Problem: Calculate n! = n × (n-1) × (n-2) × ... × 1
Output:
🔸 Example 2: Fibonacci Series
Problem: Print nth Fibonacci number
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, ...
Output:
🔸 Example 3: Sum of Digits
Problem: Find the sum of digits of a number using recursion
Output:
🔹 When to Use Recursion?
Use recursion when:
-
The problem is naturally recursive (e.g., factorial, tree traversal)
-
The solution involves repeated subproblems
-
A loop would make the solution more complex
⚠️ Caution:
-
Recursive functions may cause StackOverflowError if the base case is missing or recursion is too deep.
-
Use iteration for efficiency when possible.
Comments
Post a Comment