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

In the above image, zero plus one is one. One is third element of fibonacci series.

Also read – matrix transpose in java

Next one plus one is two. Again add one and two we will get three. Likewise if you add two and three we will get value five. In the similar way we will get the other terms.


Using for loop

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 we can display fibonacci series upto a given number,

public class FibonacciSeries 
{
   public static void main(String[] args) 
   {
      int number = 50, first = 0, second = 1;
      System.out.print("Till " + number + " : ");
      while(first <= number)
      {
         System.out.print(first + " , ");
         int sum = first + second;
         first = second;
         second = sum;
      }
   }
}

Output:

Till 50 : 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34

Related Posts