Project Euler I

I can't seem to find the error in the code that's producing a ridiculously wrong answer, I know the answer is 6 digits long as I did it before but lost the old account. It's outputting 4,519,070 which is quite a bit off.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int main()
{
    int sum, peak, c;
    peak = 1000;

     for (c = 0; c < peak; c++) {
          if (c % 3 == 0 || c % 5 == 0){
            sum = sum + c;
            cout << c << " - " << sum << endl;
          }
    }
    return 0;
}


Thanks for any help, I know that the answer is probably is right in front of my face but I got tunnel vision thinking that the code is correct.
Last edited on
You should initialize sum to 0 before using it.
+ResidentBiscuit, I have tried that, it worked. But Im not sure why it generates such a differnt result. As I though that int's were automatically set at 0.

Thanks.
C++ no primitive types are initialised. When you create a variable it'll just be junk from whatever was in that bit of memory last.

The OS can clear memory if it has to allocate your program more memory, from a section that was previously held by another process (for security reasons), but you should always initialise your variables yourself.
Topic archived. No new replies allowed.