Fibonacci series program in java

Fibonacci series is numerical series in which next number is sum of previous two numbers.
For example :
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc.
There are two ways to print Fibonacci series.
  • Using iteration
  • Using recursion

Using iteration:

Algorithm:

  • Initialise first two terms with 0 and 1
  • Find sum of first two terms. 
  • Iterate upto numberOfElements
  • Print the sum
  • Assign prev to next and next to sum to go for next two terms. 

Program:

 package org.arpit.java2blog.algo;

public class FibonnacciIterativeMain
{ 
 public static void main(String[] args)
 {
  System.out.println("Printing Fibonacci series:");
  // first two number of series
  int prev=0,next=1;
  //printing first two elements
  System.out.print(prev+" "+next);
  //number of elements to be printed
  int numberOfElements=10;
  int sum=0;
  for(int i=2;i<numberOfElements;i++)
  {
   sum=prev+next;
   System.out.print(" "+sum);
   prev=next;
   next=sum;
  }
 }

}
When you run above program, you will get following output:
 
Printing Fibonacci series:
0 1 1 2 3 5 8 13 21 34

Using recursion:

Algorithm:

  • Initialise first two terms with 0 and 1
  • Base case will be when numberOfElements becomes 0.
  • Find sum of first two terms. 
  • Print the sum
  • Assign prev to next and next to sum to go for next two terms. 
  • Call same function again and decrease numberOfElements.

Program:

 package org.arpit.java2blog.algo;

public class FibonnacciRecursionMain
{ 
 //First two number of series
 static int prev=0,next=1;
    static int sum=0;
 public static void main(String[] args)
 {
  
  System.out.println("Printing Fibonacci series:");
  
  //printing first two elements  
  System.out.print(prev+" "+next);
  //number of elements to be printed
  int numberOfElements=10;
  // -2 because we have already printed 2 elements
  printFibonacciSeriers(numberOfElements-2);
 }
 
 public static void printFibonacciSeriers(int numberOfElements)
 {
  if(numberOfElements==0)
   return;
  else
  {
   sum=prev+next;
   System.out.print(" "+sum);
   //prepare for next 2 terms
   prev=next;
   next=sum;
   printFibonacciSeriers(numberOfElements-1);
  }
  
 }
}
When you run above program, you will get following output:
 
Printing Fibonacci series:
0 1 1 2 3 5 8 13 21 34

Please go through java interview programs for more such programs.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012