package chapter34;

import javax.swing.JOptionPane;

public class ComputeFibonacciIteratively {
    /** Main method */
    public static void main(String args[]) {
        // Read the index
        String intString = JOptionPane.showInputDialog(
                "Enter an index for the Fibonacci number:");

        // Convert string into integer
        int index = Integer.parseInt(intString);

        // Find and display the Fibonacci number
        JOptionPane.showMessageDialog(null,
                "Fibonacci number at index (Iteratively) " + index + " is " + fib(index));
    }

    /** The method for finding the Fibonacci number */
    public static long fib(int n) {
        int f0 = 0, f1 = 1, currentFib;

        if (n == 0) return 0;
        if (n == 1) return 1;

        for (int i = 1; i < n; i++) {
            currentFib = f0+f1;
            f0 = f1;
            f1 = currentFib;
        }
        return f1;
    }
}


