Java Program to Print the Fibonacci Series Using Recursion

You are currently viewing Java Program to Print the Fibonacci Series Using Recursion

Java program to print the Fibonacci series using recursion

// Java program to print the Fibonacci series 
// using the recursion

import java.util.*;

public class Main {
  public static void getFibonacci(int a, int b, int term) {
    int sum;

    if (term > 0) {
      sum = a + b;
      System.out.printf("%d ", sum);

      a = b;
      b = sum;

      getFibonacci(a, b, term - 1);
    }
  }

  public static void main(String[] args) {
    Scanner X = new Scanner(System.in);
    int a = 0;
    int b = 1;
    int sum = 0;
    int term = 0;

    System.out.printf("Enter total number of terms: ");
    term = X.nextInt();

    System.out.printf("Fibonacci series is : ");
    System.out.printf("%d\t%d ", a, b);

    getFibonacci(a, b, term - 2);
  }
}

Output

Enter total number of terms: 10
Fibonacci series is : 0 1 1 2 3 5 8 13 21 34

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply