As I mentioned in another question I've been teaching myself C out of of K.N King's C Programming: A Modern Approach (2ndEdn).
I'm enjoying it, but am hoping to post the odd question here for advice if appropriate because unfortunately I don't have a tutor and some bits raise more questions then they answer!
I'm up to a question that asks me to write a program that finds the largest and smallest of four integers entered by the user... I've come up with a way to find the largest, but for the life of me can't work out how to get the smallest out. The question says that four if statements should be sufficient. Math is not my forte, I'd appreciate any advice!
#include <stdio.h>
int main(int argc, const char *argv[])
{
int one, two, three, four;
printf("Enter four integers: ");
scanf("%d %d %d %d", &one, &two, &three, &four);
if (four > three && four > two && four > one)
printf("Largest: %d", four);
else if (three > four && three > two && three > one)
printf("Largest: %d", three);
else if (two > three && two > four && two > one)
printf("Largest: %d", two);
else
printf("Largest: %d", one);
return 0;
}
I'm trying to keep it simple, as I'm only up to chapter 5 of 27!
Cheers Andrew
if (first > second)
swap(&first, &second);
if (third > fourth)
swap(&third, &fourth);
if (first > third)
swap(&first, &third);
if (second > fourth)
swap(&second, &fourth);
printf("Smallest: %d\n", first);
printf("Largest: %d\n", fourth);
The implementation of the swap()
function is left as exercise.
another way would be as such:
int one, two, three, four;
//Assign values to the four variables;
int largest, smallest;
largest = max(max(max(one, two), three), four);
smallest = min(min(min(one, two), three), four);
Not a single if statement needed ;)
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