Fibonacci series in java

Let’s learn fibonacci series in java.

Fibonacci series in java

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

fibonacci sequence java: 0, 1, 1, 2, 3, 5, 8, 13, 21 . . . . .


Let’s see program for fibonacci series in java.

public class FibonacciSeriesForLoop
{
   public static void main(String[] args)
   {
      int f = 10, num1 = 0, num2 = 1;
      System.out.print("First " + f + " fibonacci sequence: ");
      for(int a = 1; a <= f; ++a)
      {
         System.out.print(num1 + " + ");
         int total = num1 + num2;
         num1 = num2;
         num2 = total;
      }
   }
}


Output:

First 10 fibonacci sequence: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 +

In the above java program,

  • Initially first two numbers in fibonacci series are fixed. That is, 0 and 1.
  • Next number in the fibonacci series will be the sum of previous two numbers and so on. The fibonacci series continues.
  • Now the logic here is first create two variables ‘a’ and ‘b’ having values 0 and 1. Also create variable int number.
  • Then in the for loop iterate variable ‘i’ equal to one to ‘i’ less than or equal to 10 (for loop executing 10 times).
  • now ‘number’ is equal to ‘a’ plus ‘b’. Meanwhile print ‘number’ on the console using System.out.println
  • now assign value ‘b’ to ‘a’ and value ‘number’ to ‘b’. By doing this we are swapping values inside for loop.

fibonacci program in java using while loop

public class FibonacciSeriesWhileLoop
{
   public static void main(String[] args)
   {
      int a = 1, num = 15, num1 = 0, num2 = 1;
      System.out.print("First " + num + " fibonacci sequence: ");
      while(a <= num)
      {
         System.out.print(num1 + " , ");
         int total = num1 + num2;
         num1 = num2;
         num2 = total;
         a++;
      }
   }
}


Output:

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


fibonacci series using recursion in java

public class FibonacciRecursion
{
   static int num1 = 0, num2 = 1, num3 = 0;
   public static void main(String[] args)
   {
      System.out.print(num1 + " " + num2);
      FibonacciRecursion obj = new FibonacciRecursion();
      obj.fibonacciRecursive(14);
   }
   void fibonacciRecursive(int f)
   {
      if(f > 0)
      {
         num3 = num1 + num2;
         System.out.print(" " + num3);
         num1 = num2;
         num2 = num3;
         // fibonacci recursion
         fibonacciRecursive(f - 1);
      }
   }
}


Output:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610