Site icon TestingDocs.com

Fibonacci Sequence using Recursion Java Program

Introduction

In this post, we will a simple java program to print the Fibonacci sequence using recursion. The program prompts the user to enter the number of terms in the sequence to print.

Recursive formula for the fibonacci sequence is:

F(n) = F(n-1) + F(n-2)

Java Program

import java.util.Scanner;

public class FibonacciSequence {

  public static void main(String[] args) {
    Scanner keyboard=new Scanner(System.in);
    System.out.print("Enter numbers of terms (n):= ");
    int n = keyboard.nextInt();
    //Print the sequence
    System.out.print("Fibonacci sequence upto n terms:= ");
    for(int i=0;i<n;i++) {
      System.out.print(fibonacci(i)+ " ");//Invoking the recursive method
    }
  }

  /**************************************
   * Recursive method fibonacci
   * @param n
   * @return
   */
  public static long fibonacci(long n) {
    if(n==0)
      return 0;
    else if(n==1)
      return 1;
    else
      return fibonacci(n-1) + fibonacci(n-2);
  }
}

 

Output

Enter numbers of terms (n):= 10
Fibonacci sequence upto n terms:= 0 1 1 2 3 5 8 13 21 34

Screenshot

 

Java Tutorial on this website: https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/in/java/

Exit mobile version