Sum of even values in fibonacci series < 4000000

I have to sum all of the even numbers in the fibonacci series less than 4000000. I wrote this program but I don't think it works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  int main()
{
    int j = 1;
    int i = 1;
    int sum = 0;
    cout << j << endl;
    while (j<= 4000000 && i <= 4000000)
    {
        j = j + i;
        i = j - i;
        
        if ( j<= 4000000 && i <= 4000000 && j%2 == 0)
        {
            sum = j + sum;
        }
        
    }
    cout << sum << endl;
}
Why do you think it is wrong?

The two tests on i are unnecessary (because i is smaller than j, so only j matters) and you are missing
1
2
#include<iostream>
using namespace std;

in the header, but I assume that is just a copy omission.

Other than that, it seems to work (I think).
Yeah I have those in the header I just posted the main function.

And It doesn't give me the correct answer when I limit the interval to 10. And yeah youre right about i, I didn't think about that!
And It doesn't give me the correct answer when I limit the interval to 10.

Please show how you did limit and what was the result.

Are these the correct serie and the sum?
1
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
832040 *
1346269
2178309
3524578 *

sum = 4613732
Topic archived. No new replies allowed.