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

What is Fibonacci series?

  • Fibonacci number is obtained by adding two preceding numbers.
  • Fibonacci series is collection of fibonacci numbers.
    • e.g. fibonacci series is 0, 1, 1, 2, 3, 5
    • next number is fibonacci series is 3 + 5 = 8
      • fibonacci series becomes 0, 1, 1, 2, 3, 5, 8
    • next number is fibonacci series is 5 + 8 = 13
      • fibonacci series becomes 0, 1, 1, 2, 3, 5, 8, 13
  • Fibonacci series is named after Italian mathematician Leonardo of Pisa, known as Fibonacci.
  • Fibonacci numbers is defined by the recurrence relation:
    • F(n) = F(n-1) + F(n-2) where F0 = 0 & F1 = 1.

Generate fibonacci numbers in java – recursive algorithm:

  • We have shown recursive algorithm to find fibonacci number.
  • There are couple of flavors of fibonacci service
    1. 1 1 2 3 5 8 13 21 34 55
    2. 0 1 1 2 3 5 8 13 21 34 55 (with o at first number)
  • We have demonstrated point 2 in this post.
  • We have calculate the fibonacci number for input = 4.
    • recursive(4) = 3 (refer Fig 1).
print generate fibonacci series java
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 
Scroll to Top