Advertisement
brilliant_moves

FibonacciSeries.java

Oct 1st, 2012
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.97 KB | None | 0 0
  1. import java.util.Scanner;   // for user input
  2.  
  3. public class FibonacciSeries {
  4.  
  5.     /** Program:    FibonacciSeries.java
  6.     *   Purpose:    Display the first n terms in the Fibonacci Series
  7.     *   Creator:    Chris Clarke
  8.     *   Created:    01.10.2012
  9.     */
  10.  
  11.     public static void main(String[] args) {
  12.         Scanner scan = new Scanner(System.in);
  13.         int n;
  14.  
  15.         System.out.println("I will compute the first n terms in the Fibonacci Series.");
  16.  
  17.         do {
  18.             System.out.print("Please enter a value for n: ");
  19.             n = scan.nextInt();
  20.             if (n>40) System.out.println("Number too big! Must be 40 or less");
  21.             if (n<1) System.out.println("Number too small! Must be 1 or more");
  22.         } while (n>40 || n<1);
  23.  
  24.         for (int i=1; i<=n; i++) {
  25.             System.out.print(fib(i)+" ");
  26.         }
  27.     }
  28.  
  29.     public static int fib(int n) {
  30.         for (int i=1; i<=n; i++) {
  31.             switch(i) {
  32.                 case 1 :
  33.                 case 2 :    F[i] = 1; break;
  34.                 default  :  F[i] = F[i-2] + F[i-1];
  35.             }
  36.         }
  37.         return F[n];
  38.     }
  39.  
  40.     private static int[] F = new int[41];
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement