OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 14 : Recursive Methods
Unit - 2
Topic - 14 : Recursive Methods
Recursion is the process where a method calls itself, either directly or indirectly.
In Java, recursion is often used to solve problems that can be broken down into smaller subproblems of the same type.
A recursive method must have:
-
Base Case – A condition that stops further recursive calls.
-
Recursive Call – The method calls itself with a modified argument.
Example: Factorial using Recursion
Output:
How it Works (Factorial Example)
For fact(3):
-
fact(3)→ callsfact(2) -
fact(2)→ callsfact(1) -
fact(1)→ returns1(base case) -
Return chain:
-
fact(2)returns1 * 2 = 2 -
fact(3)returns2 * 3 = 6
-
✅ Key Points:
-
Base case prevents infinite recursion.
-
Recursive methods are often shorter and cleaner, but can be less efficient due to repeated method calls.
-
Common uses:
-
Mathematical problems (factorial, Fibonacci, GCD)
-
Tree/graph traversals
-
Divide-and-conquer algorithms (Merge Sort, Quick Sort)
Example 2: Fibonacci Series using Recursion
The Fibonacci sequence is a series of numbers where:
Java Program
Output
How it Works
For fib(5):
-
fib(5)→fib(4) + fib(3) -
fib(4)→fib(3) + fib(2) -
fib(3)→fib(2) + fib(1)
...and so on, until it reaches the base cases (fib(0)andfib(1)).
✅ Key Points:
-
Uses two base cases (
n==0andn==1). -
Shows how recursion can branch into multiple calls.
-
Not very efficient for large
nbecause of repeated calculations — but great for understanding recursion.
Comments
Post a Comment