Fibonacci series in Java

In Fibonacci series in java is a sum of previous two numbers. Let's take an example 0, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc.

There are two ways to write program on Fibonacci series in java

  • Without using recursion.
  • Using recursion.

Fibonacci Series in Java Without Using recursion -

class FibonacciSeriesWithRecursion {
      static int n1 = 0, n2 = 1, n3 = 0;
      static void printFibonacciSeries(int count) {
              if(count=0) {
                n3 = n1+n2;
                n1 = n2;
                n2 = n3;
                System.out.print(" "+n3);
                printFibonacciSeries(count-1);
     }
 }
public static void main(String args[]) {
        int count =10;
        System.out.println(n1+" "+n2);
        printFibonacciSeries(count-2);
 }
}

Fibonacci Series in Java Using recursion -

class FibonacciSerires {
      static int n1 =0, n2 = 1, n3 = 0;
      static void printFibonacciSeries(int count) {
            if(count>0) {
               n3 = n1+n2;
               n1 = n2;
               n2 = n3;
               System.out.println(" "+n3);
               printFibonacciSeries(count-1);
   }
}
public static void main(String args[]) {
       int count = 10;
       System.out.println(n1+" "+n2);
       printFibonacciSeries(count-2);
  }
}

Leave a Comment