Is there a simpler way to get three numbers from the user and print them in ascending order?

Viewed 731

I'm working through the exercises in Bjarne Stroustrup's book "Principles and Practice Using C++" (chapter 3 exercise 6). You're asked to make a program that takes user input (3 integer values) and prints the 3 values in order from smallest to largest. Here's my solution,

#include <iostream>
#include <string>
using namespace std;

int main()
{
    cout << "Please enter 3 integers: ";
    int num1, num2, num3;
    while (cin >> num1 >> num2 >> num3) {

    if (num1 < num2 && num2 < num3)
        cout << num1 << ", " << num2 << ", " << num3 << endl;

    if (num2 < num1 && num1 < num3)
        cout << num2 << ", " << num1 << ", " << num3 << endl;

    if (num3 < num1 && num1 < num2)
        cout << num3 << ", " << num1 << ", " << num2 << endl;

    if (num1 > num2 && num1 > num3 && num2 < num3)
        cout << num2 << ", " << num3 << ", " << num1 << endl;

    if (num1 > num2 && num1 > num3 && num2 > num3)
        cout << num3 << ", " << num2 << ", " << num1 << endl;

    if (num1 < num2 && num1 < num3 && num2 > num3)
        cout << num1 << ", " << num3 << ", " << num2 << endl;

    if (num1 == num2 && num1 < num3)
        cout << num1 << ", " << num2 << ", " << num3 << endl;

    if (num1 == num3 && num3 < num2)
        cout << num1 << ", " << num3 << ", " << num2 << endl;

    if (num1 == num2 && num1 > num3)
        cout << num3 << ", " << num2 << ", " << num1 << endl;

    if (num1 == num3 && num2 < num3)
        cout << num2 << ", " << num3 << ", " << num1 << endl;

    if (num3 == num2 && num1 < num3)
        cout << num1 << ", " << num2 << ", " << num3 << endl;

    if (num3 == num2 && num1 > num3)
        cout << num3 << ", " << num2 << ", " << num1 << endl;
   }
}

Although this worked for me, it just looks like a lot of code and I would really appreciate a more "simple" take on the problem.

6 Answers

My solution without using the array:

void order_integer() { int a, b, c;

cout << "Enter 3 integers: \n";
cin >> a >> b >> c;
if (a <= b && a <= c) {
    if (b <= c) cout << a << ' ' << b << ' ' << c << endl;
    if (c <= b) cout << a << ' ' << c << ' ' << b << endl;
}

else if (b <= a && b <= c) {
    if (a <= c) cout << b << ' ' << a << ' ' << c << endl;
    if (c <= a) cout << b << ' ' << c << ' ' << a << endl;
}

else if (c <= a && c <= b) {
    if (a <= b) cout << c << ' ' << a << ' ' << b << endl;
    if (b <= a) cout << c << ' ' << b << ' ' << a << endl;
}

}

Related