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;
}
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));
}
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
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
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
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)
A much simpler implementation is:
And C has had a boolean type since C99; see here.
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 :)