Write a Java program to generate the Fibonacci series using recursion.
This program calculates and prints the Fibonacci series up to a given number of terms using a recursive approach. Below is an explanation of how the program works:
class Main {
public static void main(String[] args) {
int terms = 5; // The number of terms in the Fibonacci series
System.out.print("Fibonacci series up to " + terms + " terms: ");
// Loop to print Fibonacci numbers from 0 to terms-1
for (int i = 0; i < terms; i++) {
System.out.print(fiboSeries(i) + " "); // Print each Fibonacci number followed by a space
}
}
// Method to calculate Fibonacci number at position n
public static int fiboSeries(int n) {
if (n == 0) {
return 0; // The 0th Fibonacci number is 0
} else if (n == 1) {
return 1; // The 1st Fibonacci number is 1
} else {
return fiboSeries(n - 1) + fiboSeries(n - 2); // Recursive calculation
}
}
}
Output:
Fibonacci series up to 5 terms: 0 1 1 2 3
Key Concepts
Fibonacci Series:
A sequence where each number is the sum of the two preceding ones.
Starts with 0 and 1: 0, 1, 1, 2, 3, 5, 8, 13, …
Recursive Approach:
The fiboSeries method calculates the Fibonacci number at position n using:
Base cases: fiboSeries(0) = 0 and fiboSeries(1) = 1
Recursive case: fiboSeries(n) = fiboSeries(n-1) + fiboSeries(n-2)
Main Method:
Specifies the number of terms (terms).
Uses a loop to compute and print Fibonacci numbers for all positions from 0 to terms-1.
Example Execution for terms = 5
Call Stack for fiboSeries(4):
Call Stack | Computation | Return Value |
fiboSeries(4) | fiboSeries(3) + fiboSeries(2) | Wait |
fiboSeries(3) | fiboSeries(2) + fiboSeries(1) | Wait |
fiboSeries(2) | fiboSeries(1) + fiboSeries(0) | 1 |
fiboSeries(1) | Base Case | 1 |
fiboSeries(0) | Base Case | 0 |
Return to fiboSeries(2) | 1 + 0 | 1 |
Return to fiboSeries(3) | 1 + 1 | 2 |
Return to fiboSeries(4) | 2 + 1 | 3 |
The series generated: 0, 1, 1, 2, 3
Advantages of Recursive Approach
Simple and elegant for smaller inputs.
Closely mimics the mathematical definition of Fibonacci numbers.
Performance Consideration
Inefficient for Large Inputs:
Each call generates two more recursive calls, leading to an exponential growth of calls.
Example: fiboSeries(5) computes fiboSeries(3) twice and fiboSeries(2) three times.