For Loop Will Not Stop Appropriately

I was working on the second question for project Euler wherein I must sum all even fibonacci numbers less than or equal to four million. I was able to do all ofit, but I keep getting the wrong answer because my code does not stop using numbers after it passes the four million mark. This I have tried using different while loops and for loops, however I still get numbers up to 9,227,465. I have clearly specified that the production of numbers must stop when it surpasses 4,000,000. The problem I am having makes no sense to me; it should work. I have simplified my code below to highlight the problem, so I realize that it is incomplete.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
int main()
{
    int x = 0, y = 1, d = 0;
    for (d = 0; d <= 4000000; d = y)
    {
        x = x + y;
        cout << x << endl;
        y = x + y;
        cout << y << endl;
    }
    return 0;
}
Last edited on
Gonna take a shot in the dark here and suggest changing it to this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int main()
{
    int x = 0, y = 1, d = 0;
    for (d = 0; d <= 4000000; d++)//make D iterate instead of equal to y
    {
        x = x + y;
        cout << x << endl;
        y = x + y;
        cout << y << endl;
    }
    return 0;
}


hope that adds up correct for you.
The condition in the for loop is only checked before each iteration, never while the actual body of the loop is running.
So in your case, in the second-to-last iteration of your loop, the program prints
2178309
3524578

which indicates that at this point, x = 2178309 and y = 3524578. Now, the loop body ends and d gets set to y (which is 3524578). Since 3524578 is still less than or equal to 4 million, the loop runs again, which is why you get the two extra values.

Perhaps a simpler explanation is this: the loop stops after the limit has been exceeded, not right before it's about to be exceeded.

You'll probably want to check inside your loop to make sure you're not running over the limit.
Last edited on
Topic archived. No new replies allowed.