Write max3() that returns the largest of three integers, correct for negative and equal values.
#include <stdio.h>
int max3(int a, int b, int c) {
if (a >= b)
return a >= c ? a : c;
else
return b >= c ? b : c;
}
int main(void) {
printf("%d %d %d\n", max3(3, 9, 4), max3(-1, -5, -2), max3(7, 7, 7));
return 0;
}
9 -1 7
One comparison picks the bigger of a and b, and a conditional operator compares it with c. Using >= makes ties work, and nothing assumes the numbers are positive.