IN C zybooks By definition the first two numbers in the Fibo

IN C++ (zybooks)

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 shown in the template. Note that the function adds up each of the Fibonacci numbers and returns the total to main. Add a newline every 10th output value. For example:

If the entered value is outside of the ranges 5 to 22 it should then output

\"Please follow the directions!\"

Solution

//code has been tested on gcc compiler

#include <iostream>

using namespace std;

int fib(int n) //recursive function for calculating fibnocci
{
if(n==0) //base condition
return 0;
else if(n==1) //base condition
return 1;
else
return (fib(n-2)+fib(n-1)); //recursive function
}
int main()
{
int n,total=0;
cout << \"Please enter a number between 5 and 22: \"; //asking user to enter number between 5 and 22
cin>>n;
if(n>=5 && n <=22) //user entered value must be between 5 and 22
{for(int i=0;i<n;i++)
{
if(i%10 != 0) //checking whether output is 10th or not
{ total=total+fib(i); //calculating total i.e sum

cout<<fib(i)<<\" \";} //printing series
else{ //if the output is the 10th one change the line
  
total=total+fib(i);
cout<<endl<<fib(i)<<\" \";} //printing series in the next line
}
cout<<endl<<\"Fibonacci # \"<<n<<\" is \"<<total<<endl; //printing total
}
else
cout<<\"Please follow the directions!\"<<endl; //if user has entered the wrong value


return 0;
}//end of code


********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 232

********OUTPUT**********


Please let me know in case of any doubt.Thanks.

IN C++ (zybooks) 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 exam
IN C++ (zybooks) 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 exam

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site