Strange output from adding elements in an array.

Jun 10, 2013 at 11:30pm
I found this awesome site "www.projecteuler.com" and for the first problem I decided to do something more complex than asked, the question is actually simple. "If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000."

I started to write this program to do it for any numbers but for some reason my output is messed up, the number is huge negative or positive. I am at a loss.

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
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace std;
void calc();
int main(){   
    int cont = 0;
    do{ 
        calc();
        cout << "1 to continue ";
        cin >> cont;
        if( cont != 1 ){
            return 0;
        }
    }while( cont == 1 );
    system("pause");
}
void calc(){
    int range=0,multiple=0;
    int total = 0;
    cout << "Input range ";
    cin >> range;
    cout << endl << "Multiple you want ";
    cin >> multiple;
    int arrayN[ range ];
    int totalArr = sizeof( arrayN )/sizeof( arrayN[0] );
    cout <<endl;
    cout << endl << "Your multiples " << endl;
    if(range%multiple == 0){
        for( int i = 0; i < range; i+multiple ){
            range-=multiple;
            arrayN[i];
            cout << range <<" "<<endl;
        } 
    }else{
        for( int i = 0; i < range; i+multiple ){
            range-=multiple;
            arrayN[i];
            cout << range-( range%multiple )<<" "<<endl;
        }
    }
    for( int i=0; i<totalArr; i++ ){
        total+=arrayN[ i ];
    }
    cout << "Sum of multiples " << total << endl;
}
Jun 10, 2013 at 11:34pm
At lines 31 and 37, the third part of your for statement is badly formed. It doesn't change the value of i, so i will always be 0, so your loops will run forever.

Also, lines 33 and 39 do nothing at all.
Last edited on Jun 10, 2013 at 11:48pm
Jun 10, 2013 at 11:47pm
Thank you for pointing those out.
Topic archived. No new replies allowed.