Java program to print Fibonacci series

Share

The program prints Fibonacci Series as the output . The functionality can be achieved in two ways by simply using a loop or recursion. Lets first get into Loops

  • Fibonacci Series Using For Loop
  • Fibonacci Series Using While Loop

A series is said to be Fibonacci series if each and every number in the given series is figured out by adding two immediate previous numbers. Here’s the sequence,  0, 1, 1, 2, 3, 5, 8, 13, 21 and so on.

Java program to print Fibonacci series using For Loop

Program:

public class FibonacciSeries {
    public static void main(String[] args) {
        int sum, firstNum = 0, secondNum, range = 10;
        System.out.println(" Fibonacci Series : ");
        secondNum = 1;
        for (int i = 1; i <= range; i++) {
            System.out.print(firstNum+" ");
            sum = firstNum + secondNum;
            firstNum = secondNum;
            secondNum = sum;
        }
}
}

Java program to print Fibonacci series using While Loop

program :

public class FibonacciSeries {
    public static void main(String[] args) {
        int sum, firstNum = 0, secondNum, range = 10, i=0;
        System.out.println(" Fibonacci Series : ");
        secondNum = 1;
        while(i <= range) {
            System.out.print(firstNum + " ");
            sum = firstNum + secondNum;
            firstNum = secondNum;
            secondNum = sum;
            i++;
        }
    }
}

Output:

Fibonacci Series : 
0 1 1 2 3 5 8 13 21 34

 

Another approach is to print the Fibonacci series recursively. In this, a method calls itself until a condition turns to false. Here’s is the code that does the same.

Java program to print Fibonacci series using recursion

program: 

public class FibonacciSeries {
    public static void main(String[] args) {
        int firstNum = 0, secondNum = 1, range = 10;
        System.out.println(" Fibonacci Series : ");
        printFibonacciSeriesRecursively(firstNum, secondNum, range);
    }

    static void printFibonacciSeriesRecursively(int num1, int num2, int range) {
        if (range < 1) {
            return;
        } else {
            System.out.print(num1 + " ");
        }
        printFibonacciSeriesRecursively(num2, (num1 + num2), range - 1);
    }
}

 

Output:

Fibonacci Series : 
0 1 1 2 3 5 8 13 21 34

This post was last modified on September 29, 2020

Sandeep Verma

Published by
Sandeep Verma
Tags: fibonacci series java program Java program to print Fibonacci series Java program to print Fibonacci series using recursion program recursion