Mroweczka - 10 months ago 37

C++ Question

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}`

`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`

Answer Source

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);
}
```