Monday, May 27, 2013

Fibonacci sequence in Java, Recursive and Non-Recursive

This is an example in Java of how to implement the Fibonacci Sequence both recursively and Non-Recursively (or using loops).  Any questions please ask, if you don't understand how a method works, make a table!

1:  // This program is written by Luis Gallego Cardona.  

2:  package com.fibonaccidemo; // Comment out if it gives you issues
3:  import java.util.Scanner;
4:  public class FibonacciDemo {
5:       public static void main(String[] args) {
6:            Scanner keyboard = new Scanner(System.in);
7:            int number = 0;      // hold the number
8:            System.out.print("Please enter the nth term of the Fibonacci: ");
9:            number = keyboard.nextInt();
10:            // Recursive call that prints out each number in the sequence up to the desired nth term.
11:            for (int i = 0; i < number; i++)
12:                 System.out.print(fibonacci(i) + " ");
13:            System.out.println();
14:            // Non-Recursive call that simply prints out the nth term in the sequence.
15:            System.out.print(fibonacciNonRecursive(number) + " ");
16:            keyboard.close();
17:       }
18:       /** fibonacciNonRecursive method
19:        * @param n The nth number to calculate
20:        * @return The nth number.
21:        */
22:       private static int fibonacciNonRecursive(int n) {
23:            if(n == 0)
24:                 return 0;
25:            int x = -1, y = 1, z =0;    
26:            for (int i = 1; i <= n; i++){
27:                 z = x + y ;
28:                 x = y;
29:                 y = z;
30:            }
31:            return y;
32:       }
33:       /**
34:        * The fibonnaci method calculates the nth term in the Fibonnaci series
35:        * @param n The nth number to calculate
36:        * @return The nth number.
37:        */
38:       private static int fibonacci(int n) {
39:                 if (n == 0)
40:                      return 0;
41:                 if (n == 1)
42:                      return 1;
43:                 else
44:                      return fibonacci(n-1) + fibonacci(n-2);
45:       }
46:  }

No comments: