Start learning free

LESSON 82 OF 347 · CONDITIONAL STATEMENTS - CHALLENGES

Absolute Difference in C#: Subtract Smaller from Larger

Practice Read the full explanation

The absolute difference is a measure of the difference between two numbers but expressed as a positive number.

In other words, it’s taking the difference between two values (x - y) and then calculating the absolute value of the result.

Create a function that takes in two numbers a and b and returns their absolute difference.

Examples:

absDiff(3, 0) ➞ 3

absDiff(0, 3) ➞ 3

absDiff(10, -1) ➞ 11

absDiff(-5, -7) ➞ 2

absDiff(6, -6) ➞ 12

absDiff(1.5, 1.5) ➞ 0

Note:

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


Hints:


If a is less then b, the absolute difference equals b - a. What if a is greater than or equal to b?

If a < b, we should return b - a. Otherwise, we should return a - b. We can use an if statement to put this in code.
STEP 1 OF 3
    Ctrl + Enter to check

    C# · CONDITIONAL STATEMENTS - CHALLENGES

    Recreating Absolute Difference in C#, explained

    Problem overview

    The method AbsDiff receives two integers, a and b, and returns the absolute difference between them: the gap between the two numbers, always expressed as a non-negative value. In other words, it is the absolute value of a - b.

    The examples show the pattern. AbsDiff(3, 0) and AbsDiff(0, 3) both give 3, so the order of the arguments doesn't matter. AbsDiff(10, -1) gives 11, AbsDiff(-5, -7) gives 2, and AbsDiff(6, -6) gives 12. The lesson also says not to use the library's absolute-value method, so the work is done with a comparison.

    Approach

    If you subtract the smaller number from the larger one, the result is never negative. So the task reduces to finding which argument is larger:

    • If a is smaller than b, the answer is b - a.
    • Otherwise a is greater than or equal to b, and the answer is a - b.

    When the two numbers are equal, both formulas give 0, so ties need no special case.

    Here is a worked case. For a = 10 and b = -1, the test 10 < -1 is false, so the method returns 10 - (-1), which is 11. For a = -5 and b = -7, the test -5 < -7 is false as well, and the result is -5 - (-7), which is 2.

    Step by step

    1. Compare. Write an if with the condition a < b, and close its braces. The body comes next.
    2. Handle the small-a case. Inside the if, return b - a;. Subtracting the smaller value from the larger one gives a result that is not negative.
    3. Handle the rest. After the if, return a - b;. No else is needed, because the return inside the if already ended the method for the case a < b. This line is only reached when a is greater than or equal to b, and then a - b is not negative.

    The solution in C#

    class Solution {
        public int AbsDiff(int a, int b) {
            if (a < b) {
                return b - a;
            }
            return a - b;
        }
    }
    

    Some details about this code:

    • Early return instead of else. When an if body always returns, the code after it behaves as the "otherwise" branch. Adding an explicit else would give the same result, and both styles are common in C#.
    • The method name. The method is AbsDiff, in PascalCase as C# methods usually are. C# is case-sensitive, so absDiff would not match.
    • Integer parameters. The signature takes and returns int. This method works on whole numbers. To compare decimals, the same logic would use double parameters and a double return type.
    • Overflow. If the two values are far apart, the true difference may not fit in an int. For example, AbsDiff(int.MaxValue, int.MinValue) should be 4,294,967,295, which is too large. C# arithmetic is unchecked by default, so the result silently wraps around. For the ordinary numbers in this lesson, this never happens.

    Edge cases and common mistakes

    • Equal inputs. AbsDiff(4, 4) falls through to a - b and returns 0.
    • Negative inputs. AbsDiff(-5, -7): here a (-5) is larger than b (-7), so the method returns -5 - (-7), which is 2. Subtracting a negative number adds its size.
    • Swapped arguments. AbsDiff(0, 3) takes the a < b branch and returns 3 - 0. A correct solution gives the same answer in both argument orders.
    • Always returning a - b. This is negative whenever a is smaller than b.
    • Using > with the wrong subtraction. If you test a > b, the matching result is a - b. Mixing the comparison with the wrong subtraction brings back negative answers.

    Testing

    • AbsDiff(3, 0) gives 3.
    • AbsDiff(0, 3) gives 3.
    • AbsDiff(10, -1) gives 11.
    • AbsDiff(-5, -7) gives 2.
    • AbsDiff(6, -6) gives 12.
    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