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