In: Computer Science
. (a) Write a C++ program to find Fibonacci numbers. (For the definition of Fibonacci numbers and the recursive formula please refer to problem 5 of Chapter 2 at page 81 in the text-book.) The program asks the user to input an integer and outputs the corresponding Fibonacci number. For example, if the user inputs 4, the program outputs the fifth Fibonacci number, which is 3. Introduce two local variables in the recursion function (suppose we call it fib(n)), one for fib(n-1) and one for fib(n-2). Run your program to make sure it works. Show the code of your program here:
Screenshot of the code:
Sample Output:
Code To Copy:
//Include the header files.
#include <iostream>
using namespace std;
//Define the function fib().
int fib(int n, int a = 0, int b = 1)
{
//Display the nth value of position.
if (n == 0)
return a;
if (n == 1)
return b;
//Call the function recursively.
return fib(n - 1, b, a + b);
}
//Define the main function.
int main()
{
//Declare the variable.
int num;
cout << "Enter the integer value: ";
cin >> num;
cout << "fib(" << num << ") = "
<< fib(num) << endl;
//Return the value for the main function.
return 0;
}