finding the minimum value of pair of numbers in array C Lang

Viewed 62

I have a question for H.W in my college in C, notice that im not allowed to use absolute value function(abs)

i need to find the minimum value between pair of numbers in given array.

assuming that the array is:

int arr[SIZE] = {1,10, 5,100,15,20,25,30,35,40};

and int diff = 0;

using this code without abs function giving me the wrong answer:

for (int i=0; i<SIZE-1; i++) {
      for (int j=i+1; j<SIZE; j++) {
          if (arr[i] - arr[j] < diff) 
                diff = (-1) * (arr[i] - arr[j]); 
      }
}

The value should be 4 and the code is returning 5. what im missing here?

1 Answers

Your code is not good because what is compared with diff and what is set to diff differs.

You can get absolute value by negating if the result is negative.

diff = -1; /* initialize to invalid value */
for (int i=0; i<SIZE-1; i++) {
      for (int j=i+1; j<SIZE; j++) {
          int score = arr[i] - arr[j];
          if (score < 0) score = -score; /* negate if negative */
          if (diff < 0 || score < diff) /* if first or new record */
                diff = score; /* update the record */ 
      }
}

In signed value on modern typical systems, we can store wider range of negative values than positive values. Therefore, it is safer to store the difference as negative value than to store as positive value on such systems.

diff = 1; /* initialize to invalid value */
for (int i=0; i<SIZE-1; i++) {
    for (int j=i+1; j<SIZE; j++) {
        int score;
        if (arr[i] < arr[j]) {
            score = arr[i] - arr[j];
        } else {
            score = arr[j] - arr[i];
        }
        if (diff > 0 || score > diff) { /* if first or new record */
            diff = score; /* update the record */
        }
    }
}

after getting the result, you can first convert the integer to string and then omit the sign mark to print the result (difference) without making it to positive integer.

char diff_str[64];
/* The + flag make the output always begin with sign mark (support diff=0 case) */
snprintf(diff_str, sizeof(diff_str), "%+d", diff);
/* +1 to skip the first character (sign mark) */
puts(diff_str + 1);
Related