Trying to get back into c++, code is working right but math is wrong somewhere

So i'm trying to get back into programming by solving Project Euler problems. For problem 2 i'm getting the correct sequence but the math isn't adding up. here's the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  //////////////////////////////////////////////////////////////////////
//Each new term in the Fibonacci sequence is generated by adding
//the previous two terms. By starting with 1 and 2, the first 10
//terms will be:
//
//1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
//
//By considering the terms in the Fibonacci sequence whose values
//do not exceed four million, find the sum of the even-valued terms.
//////////////////////////////////////////////////////////////////////

#include <iostream>

using namespace std;

int main()
{
    /* COUNTER, FIRST, SECOND, NEXT NUM, SUM*/
    int c, first = 0, second = 1, next, sum;
    /*CREATE FOR LOOP FOR FIBONACCI SEQUENCE*/
    for (c = 0; next < 4000000; c++) {
            next = first + second;
            first = second;
            second = next;
cout << next << endl;
    if (next%2 == 0)
        next += sum;
        }
cout << endl << "The sum is: " << sum << endl;
    }

/* ANSWER IS: 4613732 */


So you can see that I know what the answer is supposed to be but I want to know why i'm getting this output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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

The sum is: 2686868


As you can see the output cuts off before 4,000,000 but the mod, or math isn't acquiring the sum of all the even numbers. Please can you help me understand where I went wrong and why.

Thanks
1
2
3
4
for (c = 0; next < 4000000; c++) {
            next = first + second;
            first = second;
            second = next;


i think it's better if the code is:
1
2
3
4
5
6
7
bool first_four_million = false;
for (c = 0; (first_four_million != true); c++) {
            next = first + second;
            if (next >= 4000000 && next < 5000000)
                        first_four_million = true;
            first = second;
            second = next;

do you understand what i mean?
I don't see the sum variable initialized anywhere,next isnt initialized before the for loop either.
Did you mean to be accumulating a total into the sum variable here instead of next?

1
2
if (next%2 == 0)
        next += sum;



Edit: You could use a while loop for this. The incrementing c variable in the for loop really doesn't come into play at all in any of the calculations you do.

1
2
3
4
 while (next < 4000000) 
    {
        //do stuff
    }
Last edited on
Topic archived. No new replies allowed.