Multiple comparison of values

Hi all.
I have six integer values.
int a,b,c,d,e,f;

I need to make sure that their contents is in ascending order, or equal to the previous one.
Like: a=1, b=2, c=3 ...and so on.

I started with this:
if (!a<=b)&&(!a<=c)&&(!a<=d)&&(!a<=e)&&(!a<=f).

But then i would have to repeat the same for b:
if (!b<=c)&&(!b<=d).. and so on.

Is there a better way to do this?
Regards

Put the values in an array, and call one of the popular sort functions (easy to find on line).

Would not:

if a<b and b <c and c<e.........

meet your needs?

2 Likes

You could simplify that to

if ((b>a)&&(c>b)&&(d>c)&&(e>d)&&(f>e))

then you would not need to do any more checks.

1 Like

Hi PaulRB, that is smart!
But i think you meant : if((b>=a)&&(c>=b)&&(d>=c)&&(e>=d)&&(f>=e))
Am i correct?

3 Likes

I just realised you said

So, yes, use >= rather than >

By the way, your original attempt

if (!a<=b)&&(!a<=c)&&(!a<=d)&&(!a<=e)&&(!a<=f)

would not have worked as expected. If you check this page

You can see that the unary operator ! is higher precedence than the relational operator <= so it would get evaluated first. This would have produced some confusing results!

For example, suppose a=3 and b=2.

!a would give false. (As it would for any value of a except zero.)

true<=b would give true, because true is interpreted as 1 (and false is interpreted as zero), and 1 is less than 2.

Confused yet? Unfortunately, some aspects of the way C language works is far from ideal for beginners. Even experienced programmers who are new to C can often make this type of error.

2 Likes

Aye Up! PaulRB..
Thanks. It is all working now.
Regards.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.