I have been going through some basic exercises from a recommended beginner's book: C Programming: A Modern Approach (2nd Edition)
The question states: Use as few if statements as possible to determine the largest and smallest of four numbers entered by the user. Four if statements are sufficient. -- Since this question was asked before loops, arrays and functions were covered in the book, I am assuming that these should not be used.
Also, I know there was a similar question to this one, however none meet the requirements of what I am trying to achieve.
- Using only 4
if
statements - No for-loops.
The first thing that came to my mind was using the logical or
operator however as shown below, eight if
statements were used. Also this method is very long and not efficient:
int a, b, c, d;
printf("Enter 4 intgeres to find largest and smallest: ");
scanf_s("%d %d %d %d", &a, &b, &c, &d);
if (a > b && a > c && a > d)
printf("Largest: %d\n", a);
if (b > a && b > c && b > d)
printf("Largest: %d\n", b);
if (c > a && c > b && c > d)
printf("Largest: %d\n", c);
if (d > a && d > a && d > c)
printf("Largest: %d\n", d);
if (a < b && a < c && a < d)
printf("Smallest: %d\n", a);
if (b < a && b < c && b < d)
printf("Smallest: %d\n", b);
if (c < a && c < b && c < d)
printf("Smallest: %d\n", c);
if (d < a && d < a && d < c)
printf("Smallest: %d\n", d);
return 0;
Next, I proceeded to the following code which would be a better solution:
int a, b, c, d;
printf("Enter 4 intgeres to find largest and smallest: ");
scanf_s("%d %d %d %d", &a, &b, &c, &d);
int max = a, min = a;
if (b > max)
max = b;
else if (b < min)
min = b;
if (c > max)
max = c;
else if (c < min)
min = c;
if (d > max)
max = d;
else if (d < min)
min = d;
printf("max: %d min : %d\n", max, min);
return 0;
However, still not meeting the requirement of using 4 if
statements. I was wondering if I could shorten my code even further. Please excuse the basic nature of this question. Any suggestions would be appreciated.