Lesson 4.3 · Write it
Absolute value
A functionPython or Java6 tests, 3 of them hidden
On a phone? Put the lines in order instead
Write a function that returns the absolute value of a whole number (its distance from zero, always zero or positive).
nis a whole number from -1000 to 1000: it can be negative, zero, or positive.- If
nis negative, return its positive version. - If
nis zero or positive, return it unchanged. - Do not use any built-in absolute-value function.
Only the number your function returns is checked.
def absolute_value(n: int) -> int
You cannot use these in this question:
- abs()
This question is about writing the logic yourself, so built-in absolute-value functions are not allowed.
Examples
Your function is tested on 6 cases: the 3 examples below, and 3 hidden ones that check the rules above.
- absolute_value(-5) should return 5: a negative number becomes positive (rule 2)
- absolute_value(3) should return 3: a positive number stays the same (rule 3)
- absolute_value(0) should return 0: zero stays zero (rule 3)
public static int absoluteValue(int n)
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.
You cannot use these in this question:
- Math.abs()
This question is about writing the logic yourself, so built-in absolute-value functions are not allowed.
Examples
Your function is tested on 6 cases: the 3 examples below, and 3 hidden ones that check the rules above.
- absoluteValue(-5) should return 5: a negative number becomes positive (rule 2)
- absoluteValue(3) should return 3: a positive number stays the same (rule 3)
- absoluteValue(0) should return 0: zero stays zero (rule 3)