Recursive fibonacci method in Java

Java 8Object Oriented ProgrammingProgramming

The fibonacci series is a series in which each number is the sum of the previous two numbers. The number at a particular position in the fibonacci series can be obtained using a recursive method.

A program that demonstrates this is given as follows:

Example

 Live Demo

public class Demo {
   public static long fib(long n) {
      if ((n == 0) || (n == 1))
         return n;
      else
         return fib(n - 1) + fib(n - 2);
   }
   public static void main(String[] args) {
      System.out.println("The 0th fibonacci number is: " + fib(0));
      System.out.println("The 7th fibonacci number is: " + fib(7));
      System.out.println("The 12th fibonacci number is: " + fib(12));
   }
}

Output

The 0th fibonacci number is: 0
The 7th fibonacci number is: 13
The 12th fibonacci number is: 144

Now let us understand the above program.

The method fib() calculates the fibonacci number at position n. If n is equal to 0 or 1, it returns n. Otherwise it recursively calls itself and returns fib(n - 1) + fib(n - 2). A code snippet which demonstrates this is as follows:

public static long fib(long n) {
   if ((n == 0) || (n == 1))
      return n;
   else
      return fib(n - 1) + fib(n - 2);
}

In main(), the method fib() is called with different values. A code snippet which demonstrates this is as follows:

public static void main(String[] args) {
   System.out.println("The 0th fibonacci number is: " + fib(0));
   System.out.println("The 7th fibonacci number is: " + fib(7));
   System.out.println("The 12th fibonacci number is: " + fib(12));
}
raja
Published on 15-Feb-2019 06:10:03
Advertisements