/* Puzzle C13 -- compute the sum of the absolute value of the difference between each array element and its index */ int addDiffArray( int arr[], int size ) { int j; int diff, sum = 0; for ( j=0; j < size; j++ ) { if ( (diff = j-arr[j]) > = 0) sum += diff; else sum -= diff; } return sum; }
Comments: You might, instead of using a if
-statment,
use the function int abs(int value)
sum += (diff=j-arr[j]) > 0 ? diff : -diff;
But that expression offers no advantage in execution speed and is much harder to understand and much more likely to be buggy.
A potential problem is that the computation and the return values are int
s,
but an int
might not be big enough. Using a long
would
be safer.