Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 5

Clamp Number to Range

Easy

8 minute session

Summary

Constrain a value to lie within a specified inclusive range [low, high].

Problem statement

Write a function clamp(value, low, high) that returns value constrained to the inclusive interval [low, high]. If value is less than low, return low. If value is greater than high, return high. Otherwise return value. You may assume low <= high.

Task

Implement a function clamp(value, low, high) that returns value adjusted to the inclusive bounds low and high.

Examples

Value inside range

Input

clamp(5, 1, 10)

Output

5

Explanation

5 is between 1 and 10, so clamp returns 5.

Input format

Three numbers provided as function arguments: clamp(value, low, high). Assume low <= high.

Output format

Return a number (int or float) that lies within [low, high].

Constraints

Numbers are ints or floats. low will be less than or equal to high. Do not use external libraries.

Samples

Sample input 0

clamp(-3, 0, 7)

Sample output 0

0

Explanation 0

Value -3 is below low (0), so return 0.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:51 AM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.