By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and
ID: 3857744 • Letter: B
Question
By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two; for example, the first 6 Fibonacci numbers are 0, 1, 1, 2, 3, 5. Write a program that asks the user for a number between 5 and 22 (inclusive) and then displays that many Fibonacci numbers. YOU MUST write a function called fibonacci which is called from main as shown in the template. Note that the function adds up each of the Fibonacci numbers and returns the last one to main. Add a newline every 10th output value. For example:
Edit this code C++
#include <iostream>
#include <string>
#include <iomanip>
#include <math.h>
using namespace std;
// YOUR CODE GOES HERE
int main()
{
int num;
int fibb;
cout << "Please enter a number between 5 and 22: ";
cin >> num;
cout << num << endl;
if ((num < 5) || (num > 22))
cout << "Please follow the directions!" << endl;
else {
fibb = fibonacci(num);
cout << endl;
cout << "Fibonacci # " << num << " is " << fibb << endl;
}
}
Explanation / Answer
#include <iostream>
#include <string>
#include <iomanip>
#include <math.h>
using namespace std;
// YOUR CODE GOES HERE
int fibonacci(int n)
{
if(1 == n || 2 == n)
{
return 1;
}
else
{
return fibonacci(n-1) + fibonacci(n-2);
}
}
int main()
{
int num;
int fibb=0;
cout << "Please enter a number between 5 and 22: ";
cin >> num;
if ((num < 5) || (num > 22))
cout << "Please follow the directions!" << endl;
else {
for(int i=1;i<=num;i++)
{cout <<fibb<< endl;
fibb = fibonacci(i);
}
cout << "Fibonacci # " << num << " is " << fibb << endl;
}
}
==============================
Output:
Please enter a number between 5 and 22: 12 0 1 1 2 3 5 8 13 21 34 55 89 Fibonacci # 12 is 144
=====================
Please give me rating.I really need that
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.