C13 Answer


/* 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) to compute absolute value. Or, you may have used:

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 ints, but an int might not be big enough. Using a long would be safer.