Define a function
void order(int & a, int & b, int & c, bool ascending)

that places the values in ascending or descending order, depending on whether the last parameter is true or false . For example, if x, y and z contain the values 3,1, and 2, respectively, then after calling order(x,y,z, true ) the same variables will contain values 1, 2 and 3, respectively. On the other hand a call to order(x,y,z, false ) will cause the values to be 3,2 and 1, respectively. You may use the built in C++ function swap() if you wish.

Note that the driver will use four values for input: the three numbers to be passed into a. b, and c, followed by a 0 or a 1 (i.e. false or true ) to pass into ascending (the fourth parameter ).

Here is my solution:

void order(int &a, int &b, int &c, bool ascending)
    int temp;
        if(a < b)
        else if(b < c)
        temp = a;
        a = b;
        b = c;
        c = temp;

Here is my output:
2 1 3

Expected output:
1 2 3

I don't understand what I'm doing wrong. Is there something that needs to be added or changed in the function. I would greatly appreciate any help.

2 Years
Discussion Span
Last Post by ryantroop

You shouldn't use else if and else while you have to let the function check all coneditions and swap the values if the condition true.

also your conditions aren't correct.

it will be easier if you put the swap functions outside then check for ascending and descending and while its only three values
you can swap value x and z for ascending and descending

don't use else if or else
if y greater than z, swap them.
if x geater than y, swap them.
if y greater than z, swap them.
now you have the ascending order.

Then check for descending ( if(!ascending) ), swap x and z.

Its a reply from a newbie, sorry for any mistake.


You may want to read up on bubble sorts:


And either use a standard bubble sort, or consider the variations. Also, read about them and consider if they are the right tool for the job.

Depending on if you have learned recursion or not, out if you can make the sort a while loop instead, it may make your life easy with limited data such as this.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.