1. ## Fibonacci -- suggestions please

Hello all. I am still pretty new to C++ and I made this Fibonacci sequence thing.

What would you recommend to prevent a segmentation fault if the first to vector elements are not populated, or rather, how would you ensure the first two elements were populated?

Code:
```#include <iostream>
#include <vector>
#include <iomanip>

using namespace std;

int main(){
vector<double> fib;
double stop = 200;
double i = 1;

fib.push_back(1);
fib.push_back(1);

while(i++ <= stop)
fib.push_back(fib[i-1] + fib[i-2]);

for(i = 0; i < fib.size(); i++)
cout << setprecision(50) << fib[i] << endl;

cout << endl;

return 0;
}```
TIA!

2. I don't know what your question is. If the first two elements aren't populated, you can't do the Fibonacci sequence, so you shouldn't ever get into the situation.

But I suppose you can check that fib.size is at least 2 before trying to do the loop.

3. I guess what I am really asking is: is that how you would implement it , if there was some way I was missing that the first two values could be filled or a better way the program could be written.

4. Originally Posted by Kudose
I guess what I am really asking is: is that how you would implement it , if there was some way I was missing that the first two values could be filled or a better way the program could be written.
but you have it

Code:
```fib.push_back(1);
fib.push_back(1);```
What you have wrong - is

double i = 1;

1. Why index is double?
2. Why it is 1 if you want to access element i-2?

5. 1. It should be an int, it was left over from messing around.

2. I see the logic error in that. i should be 2.

Thanks.

6. Originally Posted by Kudose
2. I see the logic error in that. i should be 2.
No, you had it right as it was. It is initialised to 1 and then incremented to two in the while loop condition.
The only bug is using double instead of int.
An explicit push_back of the two 1's before the loop gets underway is the sensible way to do it, if you need the values all in a vector. In your code example you can just output them as you go and forget the vector though.