Fibonacci Series Java Example

Fibonacci series or Fibonacci sequence are the numbers in the following integer sequence

0,1,1,2,3,5,8,13,…..

The first two numbers in the Fibonacci sequence are 0 and 1, to obtain the sequence each subsequent number is the sum of the previous two numbers. Lets now see how to get a Fibonacci Series using recursion in java

Example

import java.util.ArrayList;
import java.util.Scanner;

public class FibonacciSeriesExample
{
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        
        //Get the number of elements for the series
        System.out.print("Number of elements to generate in a series : ");
        int n = s.nextInt();
        
        //print the fibonacci series upto number
        for (int i = 0; i <= n; i++) {
            System.out.print(fibonacciseries(i) + " ");
        }
    }

    //Method to calculate the fibonacci series
    public static int fibonacciseries(int n) {
        if (n == 0) {
            return 0;
        } else if (n == 1) {
            return 1;
        } else {
            return fibonacciseries(n - 1) + fibonacciseries(n - 2);
        }
    }
}

Output

Number of elements to generate in a series : 10
0 1 1 2 3 5 8 13 21 34 55

Leave a Reply

Your email address will not be published. Required fields are marked *