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?