*** NO i++, ONLY IF/ELSE AND WHILE STATEMENTS *** C++ By definition, the first t
ID: 3679796 • Letter: #
Question
*** NO i++, ONLY IF/ELSE AND WHILE STATEMENTS ***
C++
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 11 (inclusive) and then displays that many Fibonacci numbers. YOU MUST write a function called fibonacci which is called from main as follows:
Note that the function adds up each of the Fibonacci numbers and returns the total to main.
Explanation / Answer
#include<bits/stdc++.h>
using namespace std;
int fibonacci(int n)
{
int sum=1;//Sum of first two fibonacci terms
int prev1=0,prev2=1,next;
int i=2; //starting at i=2 for summing the terms
while(n!=i)
{
next=prev1+prev2;
prev1=prev2;
prev2=next;
sum+=next;
n--;
}
return sum;
}
int main()
{
int n,total;
cout<<"Enter a number between 5 and 11: ";
//Reading user Input
cin>>n;
if(n<5 || n>11)
{
cout<<"please follow the directions ";
}
else
{
total=fibonacci(n);//Calling fibonacci function
cout<<endl;
cout<<"Total is "<<total<<endl;
}
return 0;
}
If you have any doubts please comment below
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.