import java.util.Scanner; public class Fib1 { public static int F[]; // Saved values public static int fib(int n) { int sol1, sol2, mySol; /* ============================= Base cases ============================= */ if ( n == 0 ) { return 1; // f0 = 1 } else if ( n == 1 ) { return 1; // f1 = 1 } else /* Recursive solver */ { if ( F[n] >= 0 ) return(F[n]); sol1 = fib( n-1 ); // Solve smaller problem 1 sol2 = fib( n-2 ); // Solve smaller problem 2 mySol = sol1 + sol2; // Use solution to solve orig. proble, F[n] = mySol; // Save it for the future... return ( mySol ); // Claim credit... } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n, r; F = new int[100]; for ( int i = 0; i < F.length; i++ ) F[i] = -1; while ( true ) { System.out.print("n (< 46) = "); n = in.nextInt(); r = fib(n); System.out.println("fib(" + n + ") = " + r); } } }