RecursiveFib.java.html

  1  import java.util.Scanner;
  2  
  3  /**
  4     This program computes Fibonacci numbers using a recursive method.
  5  */ 
  6  public class RecursiveFib
  7  {  
  8     public static void main(String[] args)
  9     {  
 10        Scanner in = new Scanner(System.in);
 11        System.out.print("Enter n: ");
 12        int n = in.nextInt();
 13  
 14        for (int i = 1; i <= n; i++)
 15        {
 16           long f = fib(i);
 17           System.out.println("fib(" + i + ") = " + f);
 18        }
 19     }
 20  
 21     /**
 22        Computes a Fibonacci number.
 23        @param n an integer
 24        @return the nth Fibonacci number
 25     */
 26     public static long fib(int n)
 27     {  
 28        if (n <= 2) { return 1; }
 29        else { return fib(n - 1) + fib(n - 2); }
 30     }
 31  }