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.
if
statementsThe 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.
We can use divide n conquer approach to solve this problem.
Imagine our input = [a, b, c, d]
We want to find answer from [a,b] and [c,d]
Then merge the final solution to find the answer.
if(a > b) swap(&a,&b); // solve [a,b]
if(c > d) swap(&c,&d); // solve [c,d]
if(a > c) swap(&a,&c); // find minimum from [a,b] and [c,d]
if(d > b) swap(&b,&d); // find maximum from [a,b] and [c,d]
// a will store the minimum value.
// b will store the maximum value.
Bonus (How to Swap Number in C Language)
void swap(int *a,int *b) {
int c = *a;
*a = *b;
*b = c;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With