Iam new to programing, so be gentle!!!!
I have to program the Fibonacci Sequence up tothe first 29 numbers.
The output starts at 1 2 3 5, not 0 1 1 2.
What am I doing wrong to not get the 0 1 output.

Here is the code:

#include <iostream>
using namespace std;

int main()
{
    int f[29];
    int i;
    f[0] = 0;
    f[1] = 1;
    for (int i = 2; i <=29; i++)
    {
        f[i] = f[i-1] + f[i-2];
        cout << f[i] << endl;
        }
        system("PAUSE");
        return EXIT_SUCCESS;
        }
;

The output I get is:

1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
Press any key to continue . . .

entered

cout << [f[0], f[1]) <<endl;

before the for line, now the output starts at 1 1, where is the 0

Split your program into a calculation loop and a display loop. Your calculation loop would be what you already have, minus the output statement (Line 13). Your display loop would be the same, but start at 0 and only have the output statement.

Also, you need to be careful about your array boundaries. I noticed that your for loop runs from i=2 to i=29. This is not safe, it can cause issues. C++ arrays are 0-based which means that a declaration like int someArray[29] produces an array with indexes 0 thru 28, NOT 0 thru 29...

I noticed too, that you are using "magic numbers" (hard-coded numeric literals). This is not a good idea when you plan to reuse a number several times over. If you have to change the number, you need to change it everywhere in your program. If you miss one, it can cause issues. You are better off defining a constant, then changing the constant if the number needs to change. Example:

const int MAX_NUMBERS = 50; //define a constant to control the loops
//this constant is global so that other functions can access it too
//not all constants need to be global though.

int main() {

  //declare and initialize an array to store the numbers
  int someArray[MAX_NUMBERS] = {0, 1, 0};

  //calculation loop
  for (int i = 2; i < MAX_NUMBERS; i++) {
    someArray[i] = i;
  }
  return 0;
}

Edited 6 Years Ago by Fbody: n/a

You are misstyping the cout line before the loop.
Pay attention to braces and parentheses you have used.
Here is your code corrected :

#include <iostream>
using namespace std;
int main()
{
    int f[29];
    int i;
    
    f[0] = 0;
    f[1] = 1;
    
    cout<<f[0]<<endl<<f[1]<<endl;
    
    for (int i = 2; i <=29; i++)
    {
        f[i] = f[i-1] + f[i-2];
        cout<< f[i] << endl;
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}

P.S: I guess the last semicolon at line 18 is an extra semicolon, omit it!

This article has been dead for over six months. Start a new discussion instead.