DEV Community

Sukma Wardana
Sukma Wardana

Posted on • Originally published at swardana.com

Absolute Number in C Language

An absolute value in mathematics is defined as the non-negative value of x without regard to its sign. The notation of absolute value is a vertical bar on each side of the variable |x|. So, by theory |-16| will become 16.

Now, how could I bring this into the C programming language?

The easiest way is to use the abs API from the stdlib.

#include <stdio.h>
#include <stdlib.h>

int
main()
{
    printf("%d\n", abs(-16));
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

However, what if there is a situation in which you can't use stdlib or any libraries?

I experienced this before and was helpless. Thus, I decided to employ my Google-fu to learn how to implement absolute value without any libraries.

Then, I found the simple and easy-to-implement solutions.

#include <stdio.h>

int absolute(int x);

int
main()
{
    printf("%d\n", absolute(-20));
    return 0;
}

int
absolute(int x)
{
    return x * ((x>0) - (x<0));
}
Enter fullscreen mode Exit fullscreen mode

The source explained it better and was easy to understand. But what made me surprise is, how it leverages the characteristics of C programming language. Which is, in C we don't have a boolean data type.

In C language, to determine true or false it's using an integer value. Zero represents false and One represents true. So, let's examine how the parentheses value outcome will be:

  • (x>0): True (1) if x greater than 0, False (0) otherwise.
  • (x<0): True (1) if x less than 0, False (0) otherwise.

Let's break down when the x is a positive number.

x == 10
result = x  * ((x>0) - (x<0))
result = 10 * (  1   -   0  )
result = 10 * 1
result = 10
Enter fullscreen mode Exit fullscreen mode

Let's break down when the x is a negative number.

x == -16
result =  x  * ((x>0) - (x<0))
result = -16 * (  0   -   1  )
result = -16 * -1
result =  16
Enter fullscreen mode Exit fullscreen mode

And lastly, if the x is a zero.

x == 0
result =  x * ((x>0) - (x<0))
result =  0 * (  0   -   0  )
result =  0 * 0
result =  0
Enter fullscreen mode Exit fullscreen mode

The absolute method will never alter the x when it's a positive or zero number. But, when we set the x as a negative number we negate it by multiplying with -1 to get a positive number from x.

What an interesting solution.

Top comments (2)

Collapse
 
pauljlucas profile image
Paul J. Lucas

A much simpler implementation is:

int absolute( int x ) {
   return x < 0 ? -x : x;
}
Enter fullscreen mode Exit fullscreen mode

And C has had a boolean type since C99; see here.

Collapse
 
sukma_wardana profile image
Sukma Wardana

Oh, you're right? That's simpler and easier to understand. Thanks for sharing the solutions and info about boolean type in C. I will add it to my notes :)