Start learning free

LESSON 82 OF 338 · CONDITIONAL STATEMENTS - CHALLENGES

Recreating Abs in Go: absoluteValue with if and else

Practice Read the full explanation

The abs() function returns the absolute value of a number. This means that it returns a number's positive value. You can think of it as the distance away from zero.

Create your own function abs() that recreates this functionality.

Examples:

abs(-1.217197940) ➞ 1.21719794

abs(-544.0) ➞ 544

abs(250.3) ➞ 250.3

abs(0) ➞ 0

abs(-0.14) ➞ 0.14

Note:

Do not use the abs() function provided by Go (it will defeat the purpose of the challenge)


Hints:


You can make use of < operator with an if statement to check if n is negative.

You can add an else statement to handle the case when n is positive.
STEP 1 OF 3
    Ctrl + Enter to check

    GO · CONDITIONAL STATEMENTS - CHALLENGES

    Recreating Abs in Go, explained

    Problem overview

    The function absoluteValue receives an int, n, and returns its absolute value: the number without its sign, or equivalently its distance from zero. For -5 the answer is 5, for 250 it is 250, and for 0 it is 0.

    The task is to build this with a plain condition rather than a library function. Go's standard library has math.Abs, but it works on float64 values, not on int, so for integers you write the check yourself anyway.

    Approach

    Only negative numbers need to change. A number that is zero or positive is already its own absolute value. For a negative number, negating it flips the sign: -(-5) is 5. So the function has two cases, split on whether n is below zero, and each case returns directly.

    Step by step

    1. Test for a negative number. Write if n < 0. Go takes no parentheses around the condition, and the braces are required.
    2. Return the negation. Inside the if, return -n hands back the positive version of the number.
    3. Return the number unchanged otherwise. The else branch covers zero and every positive number, and returns n as it is. Zero belongs here, which is correct because its absolute value is zero.

    The solution in Go

    func absoluteValue(n int) int {
        if n < 0 {
            return -n
        } else {
            return n
        }
    }
    

    Some details for Go:

    • Every path returns. A function with a result type must end in a return on every route. Here both the if and the else return, and the compiler accepts that as a complete function. If you left out the else branch and its return, the function could reach its closing brace without returning, and the compiler would report missing return.
    • Unary minus. -n negates the value of n and leaves the variable itself unchanged.
    • Layout of else. } else { must stay on one line; else on a new line is a syntax error.
    • Style. Because the if branch returns, Go programmers often drop the else and write the second return after the block, as in if n < 0 { return -n } followed by return n. Both behave the same.
    • Integer types. The function works for int only. A float64 argument needs a separate function with float64 in its signature, because Go does not convert between numeric types automatically.

    Tracing two calls

    For absoluteValue(-5), the test -5 < 0 is true, so the function returns -(-5), which is 5, and the else branch is never looked at. For absoluteValue(3), the test 3 < 0 is false, so execution jumps to the else branch and returns 3. Exactly one of the two returns runs on every call.

    Edge cases and common mistakes

    • Zero. absoluteValue(0) returns 0. Using n <= 0 would also work, since -0 is 0, but < 0 says what you mean.
    • Negating everything. Returning -n in both branches would turn positive numbers negative.
    • The smallest integer. An int is 64 bits, and its smallest value is -9223372036854775808. Its positive counterpart does not fit, so negation wraps around and gives back the same negative number. Running it prints -9223372036854775808 for that input. Ordinary tests never reach this, but it is the one case where an integer absolute value cannot be right.
    • Floating-point inputs. This function takes an int. For decimals such as -0.14, the same if logic works in a function declared with float64 and returns 0.14.
    • Missing return. Forgetting a return in one branch causes the missing return compile error rather than a wrong answer.

    Testing

    • absoluteValue(-5) gives 5.
    • absoluteValue(7) gives 7.
    • absoluteValue(0) gives 0.
    • absoluteValue(-1) gives 1.
    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free