Fibonacci series are the sequence numbers, in which the next number is formed by the sum of previous two numbers.

For example – 0  1  1  2  3  5  8  13  21 . . .

here in this program we will be using a count number to determine how many Fibonacci numbers to be displayed.

Program:

import java.util.Scanner;
public class Fibonacci
{
 public static void main(String[] args)
 {
  int n1=0, n2=1, n3;
  Scanner sc = new Scanner(System.in);
  System.out.print("Enter a count number: ");
  int count = sc.nextInt();
  System.out.print("\nFibonacci series till count number is: ");
  System.out.print(n1+" "+n2); // First two numbers are printed as it is.
  for(int i=2; i<count; i++) // Please refer note given below.
  {
   n3=n1+n2;
   System.out.print(" "+n3);
   n1=n2;
   n2=n3;
  }
 }
}

Output:

Enter a count number: 8
Fibonacci series till count number is: 0 1 1 2 3 5 8 13
NOTE: 
In the FOR loop, the initial value for "i" will be 2.
As the first two numbers are printed.

You can download the pdf file of Fibonacci Series using java.

Advertisements