Computing Fibonacci Series using Recursion in Java

Recursion means a method; calling directly or indirectly themselves. Recursion is a useful programming technique. In some cases, it enables you to develop a straightforward and simple solution to an otherwise difficult problem. This post introduces you how to Fibonacci Series using Recursion in Java. Actually the Fibonacci series was named for Leonardo Fibonacci, a medieval mathematician.
The Fibonacci Series of  can be defined as follows:
 
    0 1 1 2 3 5 8 13 21 34 55 89 ... 
 
The Fibonacci series begins with 0 and 1, and each subsequent number is the sum of the preceding two. The series can be recursively defined as follows:
 
fib(0) = 0;
fib(1) = 1;
fib(index) = fib(index - 2) + fib(index - 1); index >= 2
 
import java.util.Scanner;

public class CalculateFibonacci {

       public static void main(String args[]) {
              // Create a Scanner
              Scanner input = new Scanner(System.in);
              System.out.print("Enter an index for the Fibonacci number: ");

              int index = input.nextInt();

              System.out.println("Fibonacci number at index " + index + " is "
                           + fib(index));
       }

       /** The method for finding the Fibonacci number */
       public static long fib(long index) {
              if (index == 0) {
                     // Base case
                     return 0;
              } else if (index == 1) {
                     // Base case
                     return 1;
              } else {
                     // Reduction and recursive calls
                     return fib(index - 1) + fib(index - 2);
              }
       }
}
 


 
Output of the above code listing would look like:
 
     Enter an index for the Fibonacci number: 7
   Fibonacci number at index 7 is 13
 

No comments:

Post a Comment