// Author: Keith Shomper // Date: 11/4/03 // Purpose: To demonstrate a recursive program with the Fibonacci sequence #include using namespace std; int main() { int fibonacci(int n); string suffix(int n); int n, f; // prompt the user for the value of N cout << "Which Fibonacci number would you like to compute ? "; cin >> n; f = fibonacci(n); // Display the result if (f > 0) { cout << "The " << n << suffix(n) << " Fibonacci number is " << f << endl; } return 0; } int fibonacci(int n) { if (n <= 0) { cerr << "Error: Fibonacci number not defined for non-positive number " << n << endl; return 0; } else if (n==1 || n==2) { return 1; } else { return fibonacci(n-1) + fibonacci(n-2); } } string suffix(int n) { string s; switch (n%10) { case 1: if (n%100 == 11) { s= "th"; } else { s= "st"; } break; case 2: if (n%100 == 12) { s= "th"; } else { s= "nd"; } break; case 3: if (n%100 == 13) { s= "th"; } else { s= "rd"; } break; default: s = "th"; break; } return s; }