Monday, 8 October 2018

Program to Display Fibonacci Numbers in Java

Fibonacci Numbers or Fibonacci Series is a set of numbers where the next number in the series is the sum of the preceding two numbers.
For example:
0, 1, 1, 2, 3, 5, 8, 13, 21 and so on.
Note that the first two numbers are set to 0 and 1

I am going to present two different programs  written in java to display the Fibonacci series:
1. Fibonacci Series program using for loop without recursion
2. Fibonacci Series program with recursion

Both are written and tested using Eclipse IDE which you can download  and install for free.

1. Fibonacci Number in Java without recursion

/* Program to Display Fibonacci Numbers
 * By: Kindson The Genius
 * Date: October 8, 2018
 * Usage: Free        */

public class Fibonacci {
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  //Fibonacci Numbers: 0, 1, 1, 2, 3, 5, 8, 13
  //n1, n2, n3 = n1 + n2..., 
  
  int n1 = 0;
  int n2 = 1;
  int n3 = 2;
  int count = 10;
  
  System.out.print(n1 + " " + n2);
  
  for(int i = 2; i<count; ++i)
  {
   n3 = n1 + n2;
   
   System.out.print(" " + n3);

   n1 = n2;
   n2 = n3;   
  }
 }
}

2. Fibonacci Numbers in Java with recursion

/* Program to Display Fibonacci Numbers with recursion
 * By: Kindson The Genius
 * Date: October 8, 2018
 * Usage: Free        */

public class FibonacciWithRecursion {
 
 static int n1 = 0;
 static int n2 = 1;
 static int n3 = 0;
 
 static void displayFibonacci(int count) {
  //Fibonacci Numbers: 0, 1, 1, 2, 3, 5, 8, 13
  if(count > 0) {
   n3 = n1 + n2;
   n1 = n2;
   n2 = n3;   
   System.out.print(" " + n3);
   displayFibonacci(count-1);
  }     
 }
 
 public static void main(String args[])
 {
  int count = 10;
  System.out.print(n1 + " " + n2); //display 0 and 1
  displayFibonacci(count-2); //begining from the 3rd number
 }
}

Feel free to copy this programs for free and run them to see how it works. You could change the value of the count to a larger number to view more numbers in the Fibonacci series.