Write max3() that returns the largest of three integers, correct for negative and equal values.
Solution
main.c
#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;
}
Output Verified by compiling and running
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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!