[C] Sort 3 Numbers

I am trying to write a program in C which will take in any 3 numbers and then print them out in ascending order.

Currently, it will only print out the numbers if I enter them already in ascending order. If you can help me solve this problem, I would be really thankful.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * agrv[]){    
int first, second, third;
printf("Enter three numbers"); 
scanf ("%d %d %d", &first, &second, &third);

if(third > second && third > first) {
    if(second > first){
    printf("%d %d %d", first, second, third);
    } else {
        if(first > second){
        printf("%d %d %d", second, first, third);
        } else {     
        if(second > first && second > third){
            if(first > third){
            printf("%d %d %d", third, first, second);
            } else { 
            if(third > first) {
            printf("%d %d %d", first, third, second);
                } else {   
                if(first > second && first > third){
                        if(second > third){
                        printf("%d %d %d", third, second, first);
                        } else {
                            if(third > second){
                            printf("%d %d %d", second, third, first);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
return EXIT_SUCCESS;

}

Sorry that my indentation is bad, and sorry if I am breaking any of the rules, is not my intention.

Posted Apr 9, 2016, 5:00 AM UTC

03
brakx•

You're probably over thinking and making the problem unnecessarily complicated. You only need to do 3 comparisons and swap values in the variables based on the inequality.

3
[deleted]•

[deleted]

1
John2143658709•

I'm not normally one to judge code, but I don't think anyone would want to read this. Please use else if statements instead of chaining else's together

1
Jonny0Than•

The key to this problem is to swap the values of the variables such that the smallest ends up in 'first', the middle value in 'second' and the biggest in 'third'. This is called an in-place sort. Then once you've done that, you just print the three variables in order.

1
[deleted]•

[deleted]

1