Start learning free

LESSON 81 OF 347 · CONDITIONAL STATEMENTS - CHALLENGES

Recreating Abs in C#: Absolute Value with if/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 C# (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

    C# · CONDITIONAL STATEMENTS - CHALLENGES

    Recreating Abs in C#, explained

    Problem overview

    The method Abs takes an integer n and returns its absolute value: how far the number is from zero, always as a non-negative number. The absolute value of -5 is 5, of 250 is 250, and of 0 is 0. The point of the exercise is to build this yourself, so the library method Math.Abs is off limits.

    Think of the number line. The absolute value is the distance from zero, so -3 and 3 are both three steps away and share the answer 3. A distance can't be negative, which is why the result is never below zero.

    Approach

    Only negative numbers need to change. A positive number, or zero, is already its own absolute value. So the method has two cases:

    • If n is less than 0, return the number with its sign flipped.
    • Otherwise, return n as it is.

    Flipping the sign is just the unary minus: -n. Negating a negative number gives a positive one, because -(-5) is 5.

    The same logic can be written on one line with the conditional operator, return n < 0 ? -n : n;. The lesson uses the longer if/else form, which makes each case visible. The two behave identically.

    Take n = -5. The test -5 < 0 is true, so the method returns -(-5), which is 5. Take n = 250. The test is false, so the method returns 250 unchanged.

    Step by step

    1. Test for negative. Write an if with the condition n < 0. Its body is empty for the moment.
    2. Return the negation. Inside the if, return -n; turns a negative input into its positive counterpart.
    3. Handle everything else. Add } else { on one line, and in that branch return n;. This branch also catches 0, which is correct, since the absolute value of zero is zero.

    The solution in C#

    class Solution {
        public int Abs(int n) {
            if (n < 0) {
                return -n;
            } else {
                return n;
            }
        }
    }
    

    A few C# details are worth knowing:

    • Every path returns. The method promises an int, so the compiler requires every route through it to return one. Because both the if and the else return, it is satisfied.
    • PascalCase names. C# methods conventionally start with a capital letter, so the method is Abs. C# is case-sensitive, and abs would be a different name.
    • The library method. Math.Abs does this job in practice, and the lesson avoids it so you can practise conditions.
    • An int has a lopsided range. It holds -2,147,483,648 up to 2,147,483,647, so the most negative value has no positive counterpart. In the default unchecked arithmetic, -int.MinValue wraps around and gives int.MinValue again, so Abs(int.MinValue) returns -2147483648 here. The library's Math.Abs throws an OverflowException for that input instead.

    Edge cases and common mistakes

    • Zero. Abs(0) returns 0 through the else branch. Using n <= 0 in the condition would also work, because -0 is 0, but it does extra work for nothing.
    • Returning n in the first branch. Writing return n; where return -n; belongs leaves negatives negative.
    • Writing n = -n; without a return. Assigning changes only the local parameter. The method still has to return the result.
    • Negating every input. Returning -n unconditionally flips positive numbers into negative ones.
    • Checking only positives. The method must handle both signs, so test with a negative, a positive and zero.

    Testing

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