Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the largest and smallest integers in C

Tags:

c

integer

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

like image 433
aussie_aj Avatar asked Mar 26 '11 09:03

aussie_aj


2 Answers

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.

like image 144
mgronber Avatar answered Oct 02 '22 13:10

mgronber


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 ;)

like image 44
Jordaan Mylonas Avatar answered Oct 02 '22 13:10

Jordaan Mylonas