Site icon

Generate/ print fibonacci series in java – recursive & iterative (example)

What is Fibonacci series?

Generate fibonacci numbers in java – recursive algorithm:

Fig 1: fibonacci (4) = 3

Program: print fibonacci series in java (recursive & iterative algorithm)

package org.learn;

import java.util.Scanner;

public class FibonacciSeries {

    private static int fibRecursive(int number) {
        if (number == 0 || number == 1)
            return number;

        int fibNumber = fibRecursive(number - 1) + fibRecursive(number - 2);
        return fibNumber;
    }

    private static void fibIterative(int number) {
        int prev = 0, curr = 1;
        System.out.printf("%d %d ",prev,curr);

        int fibNumber = 0;
        for (int series = 2; series < number; series++) {
            fibNumber = prev + curr;
            prev = curr;
            curr = fibNumber;

            System.out.printf("%d ",fibNumber);
        }
        return;
    }

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {

            System.out.print("1.) Enter input number : ");
            int inputNumber = scanner.nextInt();
            System.out.print("2.) Fibonacci series using Recursive method: ");
            for (int number = 0; number < inputNumber; number++) {
                //it can be optimized, for simplicity we are invoking for each number
                System.out.printf("%d ", fibRecursive(number));
            }

            System.out.print("\n3.) Fibonacci series using iterative method: ");
            fibIterative(inputNumber);
        }
    }
}

Output: print Fibonacci series in java using recursive algorithm

1. Enter input number : 5
2. Fibonacci series using Recursive method: 0 1 1 2 3 
3. Fibonacci series using iterative method: 0 1 1 2 3 

1. Enter input number : 10
2. Fibonacci series using Recursive method: 0 1 1 2 3 5 8 13 21 34 
3. Fibonacci series using iterative method: 0 1 1 2 3 5 8 13 21 34 
Exit mobile version