basics · beginner · ~15 min
Compose comparisons into a clamp.
Constrain a value to stay within a given range.
Implement int clamp(int v, int lo, int hi) that returns v limited to the inclusive range [lo, hi]: if v < lo return lo, if v > hi return hi, otherwise return v unchanged. Assume lo <= hi. No main — the grader calls it.
A value int v, and the bounds int lo and int hi (with lo <= hi).
Returns v clamped into [lo, hi], as an int.
clamp(5, 0, 10) -> 5
clamp(-3, 0, 10) -> 0
clamp(99, 0, 10) -> 10
lo snap to lo; values above hi snap to hi.A value int v and bounds int lo, int hi (lo <= hi).
v constrained to [lo, hi], as an int.
lo <= hi.
int clamp(int v, int lo, int hi) {
/* TODO */
return v;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.