Please write C++ program.
Fibonacci numbers have the property that each consecutive number is a sum of two preceding:
0, 1, 1, 2, 3, 5, 8, 13, 21 .....
Your program should ask user for the integer, and output the result, which shows Fibonacci number at that position. For example if user enters '5', program should output '3' (fifth position in the series).
Your program should use recursive function to compute and return back to the main the Fibonacci number.
Extra points: Add another function to calculate Fibonacci number using the loop (not the recursion). These two methods should give you the same result.
Main asks user for the input, calls the function(s) to calculate the Fibonacci number, and outputs the result back to the user.
For this program, you need to describe all variables and important section of code. So, please write comments for variables and describe all to text file.
#include <iostream>
using namespace std;
// RECURSION
int fib_n(int number)
{
if(number == 0 || number == 1)
return number;
// calling recursively
return fib_n(number-1)+fib_n(number-2);
}
int fib_iterative(int n)
{
int a = 0, b = 1;
if(n == 0 || n == 1)
return n;
while(n > 0)
{
int temp = a;
a = b;
b = b + temp;
n--;
}
return a;
}
int main() {
int x;
cout << "Enter a number: ";
cin >> x;
cout << fib_n(x) << " and " << fib_iterative(x) << " are same.";
}
/*OUTPUT
Enter a number: 10
55 and 55 are same.
*/
//Hit the thumbs up if you are fine with the answer. Happy Learning!
Get Answers For Free
Most questions answered within 1 hours.