Mroweczka Mroweczka - 11 days ago 6
C++ Question

Sum of different numbers in an array

I want to have a function that returns the sum of different (non duplicate) values from an array: if I have

{3, 3, 1, 5}
, I want to have sum of
3 + 1 + 5 = 9
.

My attempt was:

int sumdiff(int* t, int size){
int sum=0;
for (int i=0; i<=size;i++){
for(int j=i; j<=size;j++){
if(t[i]!=t[j])
sum=sum+t[i];
}
}
return sum;
}

int main()
{
int t[4]={3, 3, 1, 5};
cout << sumdiff(t, 4);
}


It returns
25
and I think I know why, but I do not know how to improve it. What should I change?

Answer

First of all, your loop should be for (int i=0; i<size;i++). Your actual code is accessing out of the bounds of the array.

Then, if you don't want to use STL containers and algorithms (but you should), you can modify your code as follows:

int sumdiff(int* t, int size){
    int sum=0;
    for (int i=0; i<size;i++){

        // check if the value was previously added

        bool should_sum = true;

        for(int j=0; should_sum && j<i;j++){
            if(t[i]==t[j])
                should_sum = false;
        }

        if(should_sum)
            sum=sum+t[i];
    }
    return sum;
}

int main()
{
    int t[4]={3, 3, 1, 5};
    cout << sumdiff(t, 4);
}
Comments