I need a C++ program that finds the first 100 numbers of the Fibonnaci sequence.
ID: 3669277 • Letter: I
Question
I need a C++ program that finds the first 100 numbers of the Fibonnaci sequence. Display only the last 3 numbers. List how many of those first 100 numbers are even, and how many are odd. If the sequence gets larger than you can fit in any of the available variables (that we’ve discussed to this point), you need to break out of the loop, and notify the user that the number is too large. Also let them know at which sequence number the break had to occur. (I.e. print “The number is too large. The break occurred at number ##”). Hint: The Fibonacci sequence adds the previous two numbers to create the current one in the list. The first 8 characters, for example, are: 0, 1, 1, 2, 3, 5, 8, 13...
Explanation / Answer
Here is the code for you:
#include <iostream>
#include <iomanip>
using namespace std;
int fibonacci(int n)
{
if(n == 1)
return 0;
else if(n == 2)
return 1;
else
return fibonacci(n-1) + fibonacci(n-2);
}
int main()
{
int count = 0, fib, evenCount = 0, oddCount = 0;
int x = 0, y = 0, z = 0;
cout<<"Welcome..."<<endl;
while(count < 100)
{
//cout<<"Welcome..."<<endl;
fib =fibonacci(count+1);
if(fib % 2 == 0)
evenCount++;
else
oddCount++;
count++;
//cout<<setw(10)<<fib<<" "<<x<<" "<<y<<" "<<z<<endl;
//If the sequence gets larger than you can fit in any of the available variables //
//(that we’ve discussed to this point), you need to break out of the loop,
//and notify the user that the number is too large.
//Also let them know at which sequence number the break had to occur.
if(fib < 0)
break;
x = y;
y = z;
z = fib;
}
//Also let them know at which sequence number the break had to occur.
cout<<"The number is too large. "<<endl;
cout<<"The break occurred at number "<<count<<endl;
//Display only the last 3 numbers
cout<<"The last three numbers in the series are: "<<z<<" "<<y<<" "<<x<<endl;
//List how many of those first 100 numbers are even
cout<<"The odd numbers in the series is: "<<evenCount<<endl;
//List how many of those first 100 numbers are odd
cout<<"The even numbers in the series is: "<<oddCount<<endl;
cout<<"The last number in the series is: "<<z<<endl;
}
If you need any further refinements, just get back to me.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.