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 . . .

Recommended Answers

All 4 Replies

you're not outputting values f[0] and f[1] before entering the loop.

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;
}

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.