Question
This works fine
if ((a >= 40 && a <= 50) || (a >= 60 && a <= 80))
// do something
How do I do the reverse of it?
if ((a < 40 && a > 50) || (a < 60 && a > 80))
// do something
The code does not work as expected. I want something like if not (condition)
Solution
You might want to look at De Morgan's laws.
1. !((a >= 40 && a <= 50) || (a >= 60 && a <= 80))
2. (!(a >= 40 && a <= 50) && !(a >= 60 && a <= 80))
3. ((!(a >= 40) || !(a <= 50)) && (!(a >= 60) || !(a <= 80))
4. ((a < 40 || a > 50) && (a < 60 || a > 80))
or in other words: (a < 40 || (50 < a && a < 60) || 80 < a)
OTHER TIPS
if ((a < 40 || a > 50) && (a < 60 || a > 80))
// do something
While I would recommend figuring out how to make it work properly (by rewriting it)
if (!((a >= 40 && a <= 50) || (a >= 60 && a <= 80)))
should work I believe.
You need a "OR"
if ((a < 40 || a > 50) && (a < 60 || a > 80))
Or, a NOT
if (!((a >= 40 && a <= 50) || (a >= 60 && a <= 80)))
You second example
if ((a < 40 && a > 50) || (a < 60 && a > 80))
doesn't make sense as a
cannot be both less than 40 and greater than 50 (or less than 60 and greater than 80) at the same time.
Something like
if (!((a < 40 && a > 50) || (a < 60 && a > 80)))
or
if ((a < 40 || a > 50) && (a < 60 || a > 80))
if (!((a >= 40 && a <= 50) || (a >= 60 && a <= 80)))
Assuming that you want the equivalent of
if ( not ((a >= 40 && a <= 50) || (a >= 60 && a <= 80)) )
then, if you think about the original expression, it should be
if (a < 40 || (a > 50 && a < 60) || a > 80)
The first expression is allowing a
to be a number from 40 to 50 or from 60 to 80. Negate that in English and you want a number less than 40 or between 50 and 60 or greater than 80.
De Morgan's Laws can get you an accurate answer, but I prefer code that you can read aloud and make sense of.