Find the largest of four integers using simple comparisons.
Solution
main.c
#include <stdio.h>
int max4(int a, int b, int c, int d) {
int m = a; /* the best so far */
if (b > m) m = b;
if (c > m) m = c;
if (d > m) m = d;
return m;
}
int main(void) {
printf("%d %d\n", max4(12, 45, 7, 45), max4(-3, -8, -1, -6));
return 0;
}
Output Verified by compiling and running
45 -1
Keeping a running maximum needs exactly three comparisons for four values and scales to any number of values, unlike nested if-else trees. Starting from a (not 0) handles negative numbers.
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!