0

I want to print the fibonacci series below 1000. But in my below code, I don't know why I am getting the fibonacci numbers up to the maximum size of my defined array?

int main(){
    int dp[22] = {0};

    dp[0] = 0, dp[1] = 1;
    count<<dp[0]<<" "<<dp[1]<<" ";
    for(int i=2; dp[i]<=1000; i++){
        dp[i] = dp[i-1] + dp[i-2];
        cout<<dp[i]<<" ";
    }

    cout<<endl;

    return 0;
}

Expected Output : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Actual Output : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 
cdlane
  • 40,441
  • 5
  • 32
  • 81

2 Answers2

0

The problem is the test dp[i]<=1000 in this line:

for(int i=2; dp[i]<=1000; i++){

The value of i is the index of the next array element, which always contains zero, so the test dp[i]<=1000 always returns true. I'm not sure why it doesn't cause some memory fault as you go past the end of the array. Just chance, I guess.

Perhaps the for loop rewritten as a while loop makes this clearer:

int i = 2;

while (dp[i] <= 1000) {

    dp[i] = dp[i - 1] + dp[i - 2];

    cout << dp[i] << " ";

    i++;
}

One way to make this work using a for loop:

#include <iostream>
using namespace std;

int main() {
    int dp[22] = {0};

    dp[0] = 0;
    dp[1] = 1;

    cout << dp[0] << " " << dp[1] << " ";

    for (int i = 2; ; i++) {
        dp[i] = dp[i - 1] + dp[i - 2];

        if (dp[i] <= 1000) {
            cout << dp[i] << " ";
        } else {
            break;
        }
    }

    cout << endl;

    return 0;
}
cdlane
  • 40,441
  • 5
  • 32
  • 81
0

You should rewrite your internal loop like this to make it work properly:

for(int i=2; /* dp[i]<=1000 */; i++){
    dp[i] = dp[i-1] + dp[i-2];
    if( dp[i] > 1000 ) break;   // <<---- add this line
    cout<<dp[i]<<" ";
}

And actually, I don't quite get why you need an array to print numbers, this code will print without any array just fine:

int main()
{
    int a = 0, b = 1, c;
    while( a < 1000 ) {
        std::cout << a << " ";
        c = a + b;
        a = b;
        b = c;
    }
    std::cout << std::endl;
    return 0;
}
lenik
  • 23,228
  • 4
  • 34
  • 43