basics · beginner · ~15 min

Clamp a value

Compose comparisons into a clamp.

Challenge

Constrain a value to stay within a given range.

Task

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.

Input

A value int v, and the bounds int lo and int hi (with lo <= hi).

Output

Returns v clamped into [lo, hi], as an int.

Example

clamp(5, 0, 10)    ->   5
clamp(-3, 0, 10)   ->   0
clamp(99, 0, 10)   ->   10

Edge cases

  • Values below lo snap to lo; values above hi snap to hi.

Input format

A value int v and bounds int lo, int hi (lo <= hi).

Output format

v constrained to [lo, hi], as an int.

Constraints

lo <= hi.

Starter code

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.