Determine whether integer is between two other integers
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
To check whether an integer is between two others, you compare it to a lower and upper bound. The only real design choice is whether the endpoints count as inside the range and whether the two bounds are already guaranteed to be in sorted order.
The Basic Comparison
If low <= x <= high is the rule, then the check is:
If the range should exclude the endpoints, use strict comparisons instead.
This is the whole idea in its simplest form.
Inclusive Versus Exclusive Matters
A lot of bugs come from not specifying whether the endpoints count.
For example, if x = 10 and the range is 1 to 10:
- inclusive check returns
True - exclusive check returns
False
That is why the rule should be explicit in the code rather than left to interpretation.
What If The Bounds Are Unordered?
Sometimes you do not know whether the first bound is smaller than the second. In that case, normalize them first.
This makes the function safer when caller code may pass the bounds in either order.
The Same Idea In Other Languages
In Java:
In C:
The logic is universal even though the syntax changes.
A Helper For Readability
If your code performs this check often, a named helper is clearer than repeating inline comparisons everywhere.
A good function name communicates whether the interval is closed, open, or normalized.
Why Chained Comparison Is Nice In Python
Python supports chained comparison syntax such as:
This is not just prettier than low <= x and x <= high; it also reads naturally and avoids repeating x unnecessarily.
If you are writing Python, use that feature.
Handling Non-Integer Inputs
The title says integer, but in real code you may get other numeric types or even invalid values from user input. If correctness matters, validate or convert before comparing.
The range check itself is simple. The surrounding input handling is often the more failure-prone part.
Common Pitfalls
The most common mistake is forgetting whether the interval is inclusive or exclusive.
Another mistake is assuming the lower and upper bounds are already ordered when the caller does not guarantee that.
Developers also sometimes write overcomplicated logic for what is ultimately a direct comparison problem.
Finally, in languages without chained comparison syntax, do not try to write expressions like a < b < c unless the language actually supports that meaning.
Summary
- Inclusive range checks use
low <= x <= highor the equivalent in your language. - Exclusive range checks use
low < x < high. - Normalize the bounds with
minandmaxif the inputs may be unordered. - A helper function makes repeated range checks clearer.
- Most bugs come from unclear endpoint rules, not from the comparison itself.

