Lesson 4.4 · Write it
Clamp a value
A functionPython or Java8 tests, 5 of them hidden
On a phone? Put the lines in order instead
Write a function that clamps a value into a range: if it is below the low end, return the low end; if it is above the high end, return the high end; otherwise return the value unchanged.
value,lowandhighare whole numbers.lowis always less than or equal tohigh.- If
valueis less thanlow, returnlow. - If
valueis greater thanhigh, returnhigh. - Otherwise, return
valueunchanged.
Only the number your function returns is checked.
def clamp(value: int, low: int, high: int) -> int
Examples
Your function is tested on 8 cases: the 3 examples below, and 5 hidden ones that check the rules above.
- clamp(5, 1, 10) should return 5: value is in range, returned unchanged (rule 5)
- clamp(-3, 0, 100) should return 0: value is below low, return low (rule 3)
- clamp(150, 0, 100) should return 100: value is above high, return high (rule 4)
public static int clamp(int value, int low, int high)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
Examples
Your function is tested on 8 cases: the 3 examples below, and 5 hidden ones that check the rules above.
- clamp(5, 1, 10) should return 5: value is in range, returned unchanged (rule 5)
- clamp(-3, 0, 100) should return 0: value is below low, return low (rule 3)
- clamp(150, 0, 100) should return 100: value is above high, return high (rule 4)