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.