Source of FibonacciSequence.java


  1: //FibonacciSequence.java

  3: import java.util.Scanner;

  5: public class FibonacciSequence
  6: {
  7:     /* Output the Fibonacci sequence step-by-step.
  8:        Fibonacci sequence starts as:
  9:        0 1 1 2 3 5 8 13 21 ... in which the first
 10:        two numbers are 0 and 1 and each additional
 11:        number is the sum of the previous two numbers
 12:     */
 13:     public static void computeFibonacci
 14:     (
 15:         int fibNum1,
 16:         int fibNum2,
 17:         int runCnt
 18:     )
 19:     {
 20:         System.out.println
 21:         (
 22:             fibNum1
 23:             + " + "
 24:             + fibNum2
 25:             + " = " 
 26:             + (fibNum1 + fibNum2)
 27:         );

 29:         if (runCnt <= 1) // Base case: Ran for user specified
 30:         {
 31:             // number of steps, do nothing
 32:         }
 33:         else // Recursive case: compute next value
 34:         {
 35:             computeFibonacci(fibNum2, fibNum1 + fibNum2, runCnt - 1);
 36:         }
 37:     }

 39:     public static void main(String[] args)
 40:     {
 41:         Scanner scnr = new Scanner(System.in);
 42:         int runFor; // User specified number of values computed

 44:         // Output program description
 45:         System.out.println
 46:         (
 47:             "This program outputs the\n"
 48:             + "Fibonacci sequence step-by-step,\n"
 49:             + "starting after the first 0 and 1.\n"
 50:         );

 52:         // Prompt user for number of values to compute
 53:         System.out.print("How many steps would you like? ");
 54:         runFor = scnr.nextInt();

 56:         // Output first two Fibonacci values, call recursive function
 57:         System.out.println("0\n1");
 58:         computeFibonacci(0, 1, runFor);
 59:     }
 60: }