Write a Java Program to print Fibonacci Series using Recursion.
Certainly! Below is a simple Java program that prints the Fibonacci series using recursion. The Fibonacci series is a sequence where each number is the sum of the two preceding ones, usually starting with 0 and 1.
Here's the Java code:
import java.util.Scanner;
public class FibonacciSeries {
// Recursive method to calculate Fibonacci number
public static int fibonacci(int n) {
if (n <= 1) {
return n; // Base case: return n if it's 0 or 1
}
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms in the Fibonacci series: ");
int terms = scanner.nextInt();
System.out.println("Fibonacci Series up to " + terms + " terms:");
for (int i = 0; i < terms; i++) {
System.out.print(fibonacci(i) + " ");
}
scanner.close();
}
}
fibonacci(int n): This is a recursive method that calculates the nth Fibonacci number. It checks if n
is 0 or 1 (the base cases) and returns n
in those cases. For other values, it calls itself to calculate the sum of the two preceding Fibonacci numbers.
main(String[] args): This is the main method where the program execution starts. It prompts the user to enter the number of terms they want in the Fibonacci series, then it uses a loop to print the Fibonacci numbers from 0 to the specified number of terms.
FibonacciSeries.java
.javac FibonacciSeries.java
.java FibonacciSeries
.