Fibonacci series in java

Hey guys!! Welcome to flower brackets blog. Today we are going to learn fibonacci series in java.

Fibonacci Series In Java

A fibonacci series is a sequence where each number is sum of previous two numbers

Also read – matrix transpose in java


Let’s see java program to display fibonacci series using for loop,

public class FibonacciDemo 
{
   public static void main(String[] args) 
   {
      int num = 12, first = 0, second = 1;
      System.out.print("First " + num + " series : ");
      for(int a = 1; a <= num; ++a)
      {
         System.out.print(first + " , ");
         int total = first + second;
         first = second;
         second = total;
      }
   }
}

Output:

First 12 series : 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89


In the same way we can use while loop,

public class FibonacciExample
{
   public static void main(String args[])
   {
      int a = 1, num = 15, first = 0, second = 1;
      System.out.print("First " + num + " series : ");
      while(a <= num)
      {
         System.out.print(first + " , ");
         int total = first + second;
         first = second;
         second = total;
         a++;
      }
   }
}

Output:

First 15 series : 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144 , 233 , 377


Similarly here’s the java program using recursion,

public class FibonacciRecursion 
{
   static int num1 = 0, num2 = 1, num3 = 0; 
   static void fibonacciRecursive(int count)
   { 
      if(count > 0)
      { 
         num3 = num1 + num2; 
         num1 = num2; 
         num2 = num3; 
         System.out.print(" " + num3); 
         fibonacciRecursive(count - 1); 
      } 
   }

   public static void main(String[] args) 
   {
      int number = 12; 
      System.out.print(num1 + " " + num2); 
      fibonacciRecursive(number - 2);
   }
}

Output:

0 1 1 2 3 5 8 13 21 34 55 89

Related Posts