Fibonnaci Using While Loop Help

I'm looking for any hints or tips ( because this is homework ) for correcting my program. The purpose of this program is to output the fibonacci sequence up to the 30th number if the user wants it too. But I keep getting an infinite loop that I have no clue how to fix. I'm new to c++ and a classmate recommended this site to me for programming help. Any input would be greatly appreciated.

her is the code I wrote:

#include <iostream>
using namespace std;

int main()
{
int num = 0;
int a = 0;
int b = 1;
int count = 0;
cout << "How many numbers do you want to run through? (3 min, 20 max) ";
cin >> num;
while ( num >= 3 && num <=20 )
{
b = a + b;
a = b - a;
b = a + b - a;
cout << b;
count = 10;
count++;
}
system ("pause");
return 0;
}
Last edited on
i do not kwon what you want inside while loop. but your while loop seem to be infinite loop and should.correct as

if (num>3 && num<30)
while (count < ??)
{........}

reading your reply made me realize that I was limiting the program to the 20th number, but I'm still stuck in an infinte loop. When I tried to use your solution, I get no output.
Because your loop is comparing int num which never changes in the loop. So basically at the end of the loop it goes back to while (num > 3 && num < 30) which will ALWAYS be true.
Last edited on
I see what you mean. I have moved my cout for num inside my loop, but now I get no output.
It's not solved, but I think i was supposed to post this in the beginners section. could one of the mods erase this thread?
the code like that

cin>>num;
if(num>=3 && num<=20)
while(count<3)
{
int temp=a+b;
cout<<a<<" ";
a=b;
b=temp;
count++;
};
else
cout<<"your input invalid";

the above code output :

0 1 1 2 3 5 8 13 21 .......
Last edited on
How would it output that? Assuming that count is set to 0 then your loop will only run 3 times.
Last edited on
typing error

while loop should be
while (count<num)
{
}

and the length of output depend on how many time running of the loop

Topic archived. No new replies allowed.