Java Program to Print Fibonacci Series Using Recursion

Отвечено с помощью: GPT-4o-mini отJava Q&A Hub

Вопрос:

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();
    }
}

Explanation:

  1. 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.

  2. 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.

How to Run the Program:

  1. Copy the code into a file named FibonacciSeries.java.
  2. Open a terminal or command prompt.
  3. Navigate to the directory where the file is saved.
  4. Compile the program using the command: javac FibonacciSeries.java.
  5. Run the program using the command: java FibonacciSeries.
  6. Enter the number of terms when prompted, and the program will display the Fibonacci series up to that number of terms.