MegamanEXE - 1 year ago 78
C Question

Biggest and smallest of four integers (No arrays, no functions, fewest 'if' statements)

You see, I've self-taught myself C++ (not completely, I'm still procrastinating -_-). So, now I started university and they're teaching C and they made us do a program of inputting four integers and we have to tell the largest and smallest out of them. Simple, no?

The thing is, I already have good understanding of functions and arrays. Yes, I CAN program this in arrays, no problem. But since this was the first lab, we haven't 'learned' that yet, so I can't use any of those, it'd be very simple with that.

This is what I wrote there (it feels wrong somehow).

``````#include<stdio.h>

int main(void)
{
int first, second, third, fourth;
printf("Enter four integers (separated by space): ");
scanf("%d %d %d %d", &first, &second, &third, &fourth);

if((first>second) && (first>third) && (first>fourth))
printf("\nFirst number is largest");
else if((second>first) && (second>third) && (second>fourth))
printf("\nSecond number is largest");
else if((third>second) && (third>first) && (third>fourth))
printf("\nThird number is largest");
else if((fourth>second) && (fourth>third) && (fourth>first))
printf("\nFourth number is largest");

if((first<second) && (first<third) && (first<fourth))
printf("\nFirst number is smallest");
else if((second<first) && (second<third) && (second<fourth))
printf("\nSecond number is smallest");
else if((third<second) && (third<first) && (third<fourth))
printf("\nThird number is smallest");
else if((fourth<second) && (fourth<third) && (fourth<first))
printf("\nFourth number is smallest");

printf("\n");
return 0;
}
``````

As you can see, it's too long and boring and complex. But seeing that all we've covered in class for now are loops and decision statements. Is there a more elegant way of doing this? One which uses fewer
`if`
s
? Not that there is something wrong with this, but it could be better.

P.S. This isn't exactly 'homework' or anything. I made a program, I just wanted to know what I could have done to make it better and to learn better programming practices.

As per the OP's condition

But seeing that all we've covered in class for now are loops and decision statements. Is there a more elegant way of doing this? One which uses fewer `if`s?

Only one `if` and one `else if` statement and one `for` loop can do this task. Simple and short!

``````#include <stdio.h>

int main()
{
int num, max, min;

printf ("Enter four numbers: ");
scanf ("%d", &num);
max = min = num;

for (int i = 0; i < 3; i++)
{
scanf ("%d", &num);
if (max < num)
max = num;
else if (min > num)
min = num;
}

printf ("The smallest and largest of given four numbers are %d and %d respectively.\n", min,  max);
return 0;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download