0 ? a : 0); max = (b" /> 0 ? a : 0); max = (b" /> 0 ? a : 0); max = (b"/>

Finding the max negative number, min postive number in C using ternary operato (no while loop, for loop )

87 views Asked by At
int main() {
    int a, b, c, d, e, f;
    scanf("%d %d %d %d %d %d", &a, &b, &c, &d, &e, &f);

    int max = (a < 0 ? a : 0);
    int mmin = (a > 0 ? a : 0);
    
    max = (b < 0 && b > max ? b : max);
    max = (c < 0 && c > max ? c : max);
    max = (d < 0 && d > max ? d : max);
    max = (e < 0 && e > max ? e : max);
    max = (f < 0 && f > max ? f : max);
    
    mmin = (b > 0 && b < mmin ? b :mmin);
    mmin = (c > 0 && c < mmin ? c :mmin);
    mmin = (d > 0 && d < mmin ? d :mmin);
    mmin = (e > 0 && e < mmin ? e :mmin);
    mmin = (f > 0 && f < mmin ? f :mmin);
    
    printf("The max negative number is: %d\n", max);
    printf("The min positive number is: %d\n", mmin);
}

So.. this is my code and when i try to run it, it has a problem with the output, example with " 1 -2 3 -4 5 -6 ", it gave me the min positive is 1 and max negative is 0 ( but not -2 ), anyone knows why ?

1

There are 1 answers

1
Mark Adler On

Your code can, at best, give you one of the two things you're looking for. If the first number is positive, you will get the smallest positive value, but zero for the other. Vice versa if the first number is negative. The problem is setting max, mmin, or both to zero for the first number (a). Once either is zero, it will remain zero regardless of the subsequent values.

To fix this, your subsequent checks need to see if the current max or mmin is zero, and not use it for comparison in that case. If it is zero, then simply set it if the value is less than or greater than zero. If max or mmin is not zero, then you can do the compare to see if you should update it. (This is better than setting them initially to INT_MIN and INT_MAX, because you would then not be able to tell if an input was one of those or not.) So:

    int max = a < 0 ? a : 0;
    int min = a > 0 ? a : 0;
    max = b < 0 && (max == 0 || b > max) ? b : max;
    min = b > 0 && (min == 0 || b < min) ? b : min;
    max = c < 0 && (max == 0 || c > max) ? c : max;
    min = c > 0 && (min == 0 || c < min) ? c : min;
    ...

At the end, you can check if either of those is still zero, and if so, report that there were no such values (no negatives or no positives, or neither) in the input.