Thursday, January 21, 2016

C/C++ language. A funny challenge: sorting numbers without using arrays

From programmr.com: 

"Write a program which accepts 3 integers and sort them in ascending order."

Of course, we can use the ternary operator or some if/else statements in order to find the largest and smallest of the three numbers, respectively.

Once done that, we need to find the intermediate value using if/else statements.

The code and the print screen:


// sorting three numbers without arrays

#include <iostream>

using namespace std;

int main()
{
    int a, b, c, min, max, inter;
     
    cout <<"Gimmie three numbers and I will sort them for you.\nNumber a: ";
    cin >> a;
    cout <<"Number b: ";
    cin >> b;
    cout <<"Number c: ";
    cin >> c;
     
    min = (a <= b)?a : b;
    min = (min <= c)?min : c;
     
    max = (a >= b)?a : b;
     max = (max >= c)?max : c;
    
    if((a <= b && b <= c) || (c <= b && b <= a)) inter = b;
    if((a <= c && c <= b) || (b <= c && c <= a)) inter = c;
    if((b <= a && a <= c) || (c <= a && a <= b)) inter = a;
    
    cout << min <<" "<< inter <<" "<< max;
    return 0;
}
   





Anonther solution, using just if/else nested statements:

//sorting three without arrays v2.0



#include <iostream>

using namespace std;

int main()
{
    int a, b, c, min, inter, max;
    cout <<"Gimmie three numbers and I will sort them ascending for you.\nNumber a: ";
    cin >> a;
    cout <<"Number b: ";
    cin >> b;
    cout <<"Number c: ";
    cin >> c;
    if(a <= b)
    {
         if(b <= c)
         {
              inter = b; min = a; max = c;
         }
         else
         {
              max = b;
              if(c > a)
              {
                   inter = c;
                   min  = a;
              }
              else
              {
                   inter = a;
                   min = c;
              }
         }
    }
    else if (b >= c)
    {
         max = a;
         min = c;
         inter = b;
    }
    else
    {
        min = b;
        if(a >= c)
        {
             max = a;
             inter = c;
        }
        else
        {
             max = c;
             inter = a;
        }
    }
    cout << min <<" "<< inter <<" "<< max;
    return 0;
}



No comments:

Post a Comment