Outputting Fibonacci Sequence As An Array

Thank you for reading my post. I need help with my code. It keeps outputting garbage numbers. The assignment asks to ouput the fibonacci sequence up to a limit determined by the user. Below is my code. Thanks so much for your help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
using namespace std;
int main()
{
	int limit, fib[50];
	cout << "enter limit: ";
	cin >> limit;
	
	for(int i=0; i<50; i++)
	{
           for (int i =0; i <50; i++)
		{
	           if(i == 0)
	              {
			fib[0] = 0;
		      }
		   else if(i ==1)
	              {
			fib[1] = 0;
		      }
		   fib[i] = fib[i-1] + fib[i-2];
			if(fib[i] >= limit)
			    {
			      break;
			    }
			
		}
            if(fib[i] >= limit)
               {
                  break;
               }
            cout << fib[i] << endl;
       }
	

	
cout << endl;
system ("pause"); 
return 0;
}
If you need to use an array, it only needs three elements:

fib[0] initialized to one
fib[1] initialized to one

after that, fib[2] is the sum of fib[0] and fib[1], fib[0] = fib[1], fib[1] = fib[2]
repeat until fib[2] >= target

fewer than 15 lines of code, overall. Maximum two loops, if you want the user to keep entering numbers.

I would suggest you start over, and start by stating exactly what a fibonacci number is.
I don't understand your explanation. State it where exactly?
fib[1] = 1

Fix your line 19 and you'll be closer.

I also recommend getting rid of lines 11, 12, and 22 through 27.

You need another else before line 21. (Do you see why?)

Work on your indentation -- it'll help you immeasurably.

Hope this helps.

@PCrumley48
fib[0] = 0

Last edited on
Topic archived. No new replies allowed.