Whats wrong in my code! I want to print Fibonacci Series with values less than 4000000

94 views Asked by At

I think I there is some problem in implementation of my loop! Here's my code.

#include <iostream>
using namespace std;

int main()
{
    int i=2;
    long long int FiboNo[100];
    FiboNo[0] = 1;
    FiboNo[1] = 2;
    do{
        FiboNo[i]=FiboNo[(i-1)]+FiboNo[(i-2)];
        cout<<FiboNo[i]<<endl;
        i++;
    }while(FiboNo[i]<4000000);
    return 0;
}
1

There are 1 answers

0
Uma Kanth On BEST ANSWER
do {
    FiboNo[i] = FiboNo[(i - 1)] + FiboNo[(i - 2)];
    cout << FiboNo[i] << endl;
    i++;
} while (FiboNo[i] < 4000000);

You are incrementing i before you compare.

do {
    FiboNo[i] = FiboNo[(i - 1)] + FiboNo[(i - 2)];
    cout << FiboNo[i] << endl;
} while (FiboNo[i++] < 4000000);

is what you want to do.

Here's what's happening:

i 2
fibo[2] is 2
now i is 3
fibo[3] is 0

This has no problem, when fibo[someIndex] reaches the limit. It wont come out, because your value is always a 0.