1

I am sorry for my bad English I will try my best so you can understand me :) I am studying C++ from Stroustrup's book and I'm trying to do this excersise with sorting 3 numbers using if-statements. I think I've done pretty good job writing this code, at least I feel so. I have done some calculations on paper so I could understand it better, and I came up with this code:

#include <iostream>

int main()
{
    int val1;
    int val2;
    int val3;

    std::cout << "Please enter the 1st number: ";
    std::cin >> val1;
    std::cout << "Please enter the 2nd number: ";
    std::cin >> val2;
    std::cout << "Please enter the 3rd number: ";
    std::cin >> val3;

    if (val1 > val2)
    {
        if (val2 > val3)
        {   
            std::cout <<  val3 << ' '  << val2 << ' ' << val1;
        }
        else
        {
            if (val1 > val3)
                std::cout << val2 << ' ' << val3 << ' ' << val1;
            else
                std::cout << val2 << ' ' << val1 << ' ' << val3;
        }
    }
    else
    {
        if (val2 > val3)
        {
            if (val3 > val1) std::cout << val1 << val3 << val2;
            else std::cout << val3 << val1 << val2;
        }
        else
        {
            std::cout << val1 << val2 << val3;
        }


    } 

My question is: Is there anything I could do to improve this code? I've tried pretty much everything I could, but I can't get it to have less if-statements, I don't know if it's the least if's I can get with this exercise, please help me out :)

2 Answers2

2

Here's a simple method, which works in a "bubble sort" like manner

#include <utility>
#include <iostream>

int main() {
    int a, b, c;
    a = 5; b = 3; c = 4;
    if ( a > b ) std::swap( a, b );
    if ( b > c ) std::swap( b, c );
    if ( a > b ) std::swap( a, b );

    std::cout << a << ", " << b << ", " << c << std::endl;
}
ChrisMM
  • 8,448
  • 13
  • 29
  • 48
1
struct Compare3Result
{
     int min, mid, max;
};

Compare3Result compare3(int a, int b, int c)
{
    if (a < b)
    {
        if (b < c)
            return {a, b, c};
        // else
        if (a < c)
            return {a, c, b};
        // else
        return {c, a, b};
    }
    // else
    if (b < c)
    {
        if (a < c)
            return {b, a, c};
        // else
        return {b, c, a};
    }
    // else
    return {c, b, a};
}

int main ()
{
    auto result = compare3(3,2,1);

    std::cout << result.min << result.mid << result.max;
} 
Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31
  • 1
    Seems identical logic than OP. – Jarod42 Jan 30 '20 at 18:50
  • I'd agree with @Jarod42. OP is trying to reduce the number of if statements. Yours has the same amount, the only difference is where the output is, and you use `<` instead of `>`, but you have the same number of `if`s. I think your version is much cleaner than OP's, but I'm not sure its really answering the question. – ChrisMM Jan 30 '20 at 19:03