Simpler way of sorting three numbers
Is there a simpler and better way to solve this problem because
- I used too many variables.
- I used so many
if else
statements - I did this using the brute force method
Write a program that receives three integers as input and outputs the numbers in increasing order.
Do not use loop / array.
#include <stdio.h>
main(){
int no1;
int no2;
int no3;
int sto;
int hi;
int lo;
printf("Enter No. 1: ");
scanf("%d", &no1);
printf("Enter No. 2: ");
scanf("%d", &no2);
printf("Enter No. 3: ");
scanf("%d", &no3);
if (no1>no2) {
sto=no1;
lo=no2;
} else {
sto=no2;
lo=no1;
}
if (sto>no3) {
hi=sto;
if(lo>no3){
sto=lo;
lo=no3;
}else {
sto=no3;
}
}else hi=no3;
printf("LOWEST %d\n", lo);
printf("MIDDLE %d\n", sto);
printf("HIGHEST %d\n", hi);
getch();
}
if (a > c)
swap(a, c);
if (a > b)
swap(a, b);
//Now the smallest element is the 1st one. Just check the 2nd and 3rd
if (b > c)
swap(b, c);
Note: Swap changes the values of two variables.
Call the three variables x
, y
, and z
, then:
if (x > y) swap(x, y);
if (y > z) swap(y, z)
if (x > y) swap(x, y);
Writing the swap
function is left as an exercise for the reader. Hint: you may have to use pointers.
#include <stdio.h>
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
int main(){
int a, b, c;
int hi;
int lo;
printf("Enter No. 1: ");
scanf("%d", &a);
printf("Enter No. 2: ");
scanf("%d", &b);
printf("Enter No. 3: ");
scanf("%d", &c);
lo = min(min(a, b), c);
hi = max(max(a, b), c);
printf("LOWEST %d\n", lo);
printf("MIDDLE %d\n", a+b+c-lo-hi);
printf("HIGHEST %d\n", hi);
getchar();
}