Java program to print Fibonacci Series

In this tutorial, we will print fibonacci series.
According to wikipedia:
In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones:[1][2]

0,1,1,2,3,5,8,13,21,34,55,89,144..

Here is simple program to print fibonacci series..

import java.util.Scanner;

public class FibSeriesPrinter
{
    public static void main(String args[])
    {
        int first=0, second=1, nxt=0, len;
        Scanner scan = new Scanner(System.in);

        System.out.print("Enter length of series you want to print ? ");
        len = scan.nextInt();

        /* print first two nos of the Fibonacci series */

        System.out.print("Fibonacci Series : " + first + "  " + second + "  ");
        nxt = first + second;

        /* decrease the len by 2, as first two numberswe already printed */

        len = len - 2;

        while(len>0){
            System.out.print(nxt + "  ");
            first = second;
            second = nxt;
            nxt = first + second;
            len--;
        }

    }
}

Output:

Enter length of series you want to print ? 7
Fibonacci Series : 0 1 1 2 3 5 8

That’s all about printing fibonacci series.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.