Fibonacci Series in Java - Java Program to Print Fibonacci Series



Fibonacci Series in Java :

  • Fibonacci series is a series where the next number is the sum of previous two numbers. For example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc. The first two numbers of fibonacci series are 0 and 1..

Sample Code

import java.util.Scanner;

public class fibonacci 
{
  public static int FibonacciSeries(int n) 
  {
    int firstnumber = 0, secondnumber = 1, result = 0;
    if (n == 0) return 0;
    if (n == 1) return 1;
    for (int i = 2; i <= n; i++) {
      result = firstnumber + secondnumber;
      firstnumber = secondnumber;
      secondnumber = result;
    }
    return result;
  }
  public static void main(String[] args) 
  {
    System.out.println("Enter the length of the Fibonacci Series: ");
    Scanner sc = new Scanner(System.in);
    int length = sc.nextInt();
    for (int i = 0; i < length; i++) 
    {
      System.out.print(FibonacciSeries(i) + " ");
    }
    System.out.println();
  }
}

Output

Enter the length of the Fibonacci Series: 9
0 1 1 2 3 5 8 13 21

Related Searches to Fibonacci Series in Java - Java Program to Print Fibonacci Series