Java Program Fibonacci Series Using Recursion

In this Java program, I show you how to calculate the Fibonacci series of a given number using a recursive algorithm where the fibonacci() method calls itself to do the calculation.

Fibonacci series is a sequence of values such that each number is the sum of the two preceding ones, starting from 0 and 1. The beginning of the sequence is thus:
```
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ...
```

Fibonacci Series Java Program Using Recursion

Java Fibonacci series program using a recursive algorithm where the fibonacci() method calls itself to do the calculation.
/**
 * 
 */
package net.javaguides.corejava.programs;

import java.math.BigInteger;
import java.util.Scanner;

/**
 * The program calculates the fibonacci sequence of given number.
 * @author Ramesh Fadatare
 *
 */
public class FibonacciRecursiveProgram {
 public static BigInteger fibonacci(int n) {

  if (n <= 1) return BigInteger.valueOf(n);

        return fibonacci(n - 2).add(fibonacci(n - 1));
    }

    public static void main(String[] args) {

     Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int n = scanner.nextInt();
        
        for (int i = 0; i < n; i++) {
            BigInteger value = fibonacci(i);
            System.out.print( value + "\t");
        }
        
        scanner.close();
    }
}
Output:
Enter a number: 10

0 1 1 2 3 5 8 13 21 34

Related Java Programs

Comments