I want to see if a variable is between a range of values, for example if x is between 20 and 30 return true.
What’s the quickest way to do this (with any C based language)?
It can obviously be done with a for loop:
function inRange(x, lowerbound, upperbound)
{
for(i = lowerbound; i < upperbound; i++)
{
if(x == i) return TRUE;
else return FALSE;
}
}
//in the program
if(inRange(x, 20, 30))
//do stuff
but it’s awful tedious to do if(inRange(x, 20, 30)) is there simpler logic than this that doesn’t use built in functions?
The expression you want is
EDIT:
Or simply put in in a function
Python has an
inoperator:Also in Python, and this is pretty cool — comparison operators are chained! This is totally unlike C and Java. See http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Comparison_operators
So you can write
In Python
-10 <= -5 <= -1is True, but in C it would be false. Try it. 🙂