Software & Finance





Java - Fibonacci Series





I have given here a Java program that prints out Fibonacci Series. The logic for fibonacci series very simple. It starts with 0 and 1. The next subsequent term is the sum of the previous two terms.

 

 

Source Code


import java.lang.*;

import java.util.*;

import java.io.*;

 

 

class FibonacciSeries

{

 

    public static int ReadInteger()

   {

        try

        {

              InputStreamReader input = new InputStreamReader(System.in);

              BufferedReader reader = new BufferedReader(input);

              return Integer.parseInt(reader.readLine());

        }

        catch (Exception e)

        {

 

              e.printStackTrace();

              return 0;

        }

   }

  

   public static void main(String[] args)

   {

      int f1 = 0, f2 = 1, f3;

      System.out.println("Program for Fibonacci Series");

      System.out.print("Enter the maximum number for Fibonacci Series: ");

      int n = ReadInteger();

 

      System.out.format("\n\nPrinting Fibonacci Series from 0 - %d\n\n", n);

      System.out.format("%d\t%d\t", f1, f2);

      while (true)

      {

            f3 = f1 + f2;

            if (f3 > n)

               break;

            System.out.format("%d\t", f3);

            f1 = f2;

            f2 = f3;

      }

      System.out.println();

   }

}

 

Output