Fibonacci Stuck on Infinite loop

I'm trying to get this program to display the fibonacci sequence to the any digit between 3 & 30. It is stuck on an infinite loop.

here 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;
}
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;
if(num >= 3 && num <= 20)
{
while (num > 0)
{
b = a + b;
a = b - a;
b = a + b - a;
cout << b;
count = 10;
count++;
num--;
}
}
system ("pause");
return 0;
}
I never thought of using a loop. But thanks a ton. It works perfectly. I'm new to C++ but how did you know to use the If ?
Last edited on
I'm so confused about this bit...
1
2
count = 10;
count++;

Your assigning 10 to count every time it goes through the loop, then adding 1 so that it is 11. So every time this loop goes through, count is the exact same.. I don't understand the point? I also don't see where count is even used, but I imagine this isn't your full code (even though it looks like it.)
Last edited on
As TheNoobie said, Im not so sure about that either. Especially that you have int count = 0 outside the loop not used, and then make it 10 without even using it.
I really don't get it either. But it works. Maybe the int count = 0 is ignored because I changed it to 10 inside the loop.
generally in programming its not good to say "i dont understand it but it works" because its hard to get better that way :o
anyhow heres my code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using std::cout;
using std::endl;
using std::cin;

int main(void)
{	
	int length;
	cout << "How many numbers would you like to print out? ";
	cin >> length;
	int* sequence;
	sequence = new int[length];
	sequence[0] = 1;
	sequence[1] = 2;
	for (int i = 2; length > 0; length--, i++)
	{
		sequence[i] = sequence[i - 1] + sequence[i - 2];
		cout << sequence[i] << endl;
	}

	delete [] sequence;
	sequence = 0;
	return 0;
}
Topic archived. No new replies allowed.