Clamp to Range
Programming Basics · C++
TASK
Problem
Given integers `x`, `l`, and `r` with `l ≤ r`, print `x` limited to the interval `[l, r]`: `l` if `x < l`, `r` if `x > r`, otherwise `x`.
EXAMPLE
Example
-5 0 10
0
LIMITS
Constraints
|x|, |l|, |r| ≤ 10^9; l ≤ r.
LEARN
Theory for this problem
+
These exercises combine arithmetic, comparisons, and small branches. Keep each condition explicit and easy to verify.
Connection to “Clamp to Range”: here, intermediate values are best kept in named variables so the formula stays readable and data types remain clear.
NEED HELP?
Hints
+
['Break the task into a few simple checks instead of compressing everything into a clever expression.', 'After solving “Clamp to Range”, verify the algorithm on your own small example and on an allowed boundary case. Print only the required result with no extra text.']
ANSWER
Solution
+
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
long long x,l,r;
cin >> x >> l >> r;
cout << min(max(x,l),r) << '\n';
return 0;
}