Calculating the Absolute Value

Difficulty: ★ ☆ ☆ ☆

The BASIC Handbook cover
I started my technology writing career at a computer book publishing house, CompuSoft. It’s no longer around, but I do recall ghost writing books such as the BASIC Handbook, which was an encyclopedia of the BASIC programming language. The first command listed in this book was ABS.

The ABS command returns the absolute value of an integer, which is its positive value: ABS(5) is 5. ABS(-200) is 200.

I’ve seen absolute values used when dealing with exponentiation as some calculations result in both positive and negative values. Whatever. Still, it’s easier for me to explain how to write a C program to calculate that absolute value than it is for me to understand math.

Before you protest, I know that the C library hosts a slate of absolute value functions. These depend on the integer size:

abs() for int values
labs() for long values
llabs() for long long values

Do not use any of these functions for your solution to this exercise! Instead, your challenge is to write a program that prompts the user for an integer (int) value and outputs its absolute value.

Here’s are some sample runs of my solution:

Enter an integer: 5
The absolute value is 5

Enter an integer: -200
The absolute value is 200

This task may not seem too difficult (hence only one star), but a quirk exists when returning the value of some negative integers. I share this quirk along with my solution, but please try this exercise on your own.

2 thoughts on “Calculating the Absolute Value

  1. Here’s the quirky thing about using an unsigned integer instead of a signed: When you input a negative value, the result is negative – at least for my solution:

    Enter an integer: -200
    The absolute value is -200

    Weird, huh?

Leave a Reply