/* Faan Tone Liu January 29, 2003 Demo program for comp 1672 Calculates Fibonacci numbers using a recursive algorithm */ #include using namespace std; // prototype for our recursive function that calculates fibonacci numbers. // Returns the value of the nth fibonacci number int fib(int n); int main() { int n; cout << "This program calculates a fibonacci number for you." << endl; cout << "What element of the fibonacci sequence do you want? "; cin >> n; cout << "Element number " << n << " of the fibonacci sequence is " << fib(n) << endl; } // This function calculates the nth fibonacci sequence recursively // Base case: If n== 0, big error! If n==1 or n==2 , answer is 1 because // the first two terms of the fibonacci sequence are both 1 // Recursive step: fib(n) = fib(n-1)+fib(n-2) int fib(int n) { if (n==0) { cout << "Program error...Fibonacci function called with n = 1\n"; exit(1); // Exit with error status } if (n==1 || n ==2) return 1; return fib(n-1) + fib(n-2); }