Fibonocci Sequence

Hi there, I am currently taking an intro to c++ class and need help with a homework assignment I have:

--------------------------------------------------------------------------------------
Write a C++ program that performs the following tasks:
Prompt the user to specify how many Fibonacci numbers to calculate.
Calculate the specified Fibonacci sequence using only
int
data types.
Output an error if your Fibonacci computation exceeds the highest
possible value for an
int
data type. In other words, abort the program
if a ”rollover” occurs.
Output the final Fibonacci value.

---------------------------------------------------------------------------------------

Here's the code I typed so far, but it's not doing anything:

#include <iostream>

using namespace std;
int main()
{
int current=0, prev=1, prev2=1, fibnum;
cout << "Enter the number of Fibonacci numbers to compute: ";
cin >> fibnum;

if (fibnum <=0)
{
cout << "Error: Enter a positive number: ";
}

else (fibnum > 0);
{
current = prev + prev2;
prev = prev2;
prev2 = current;
current++;

cout << "," << fibnum;
cout << endl;
}
return 0;
}

If someone can help me out then that would be great! Thanks.
Last edited on
You want to put this in a loop, which terminates when the amount of times the loop has executed is = fibnum.
1
2
3
4
5
6
7
current = prev + prev2;
prev = prev2;
prev2 = current;
current++;

cout << "," << fibnum;
cout << endl;


Also, your starting values for prev and prev2 are incorrect. The first terms of the Fibanacci sequence are 0,1,1 and you are not going to get those with your program.

Nothing should go after else, it should just be else on its own.

You are outputting fibnum, but you want to output current.
Last edited on
Thank you so much for the suggestion! It really helped me get things in line and get it to work.
Topic archived. No new replies allowed.