Abs function in C

In the C programming language, abs function is short for “Absolute Value” that describes the distance of a number on the number line starting from 0 without considering the direction. The abs value, that is, absolute value of the number is always a positive value, that is, a distance can never be negative. The abs() function returns the absolute value of an integer. In the C programming language, the abs() function can be applied to ANSI/ISO 9899-1990.

Stdlib.h is a header of a general-purpose standard library of the C programming language that includes functions including memory allocation, process control, conversions, and so on. Stdlib is short for “standard library”.

Stdlib.h is a header that defines variable types, macros, and various functions for performing general compiler functions. Some of the variable types include size_t, wchar_t, div_t, ldiv_t; macros include NULL, EXIT_FAILURE, EXIT_SUCCESS, RAND_MAX, MB_CUR_MAX;

Syntax:

E.g.:

Output:

Different types of approaches:

1. Naive based approach: the absolute value of any number is always a positive number. For any positive integer, the absolute value is the number itself and for any negative number, the absolute value is (-1) multiplied by the given negative number.

E.g.:

Output:

• Using inbuilt abs() function: the C programming language has an inbuilt function that defines the absolute function abs() present within stdlib.h library and finds absolute value of any number as defined.

E.g.:

Output:

• Bitmasking: In the C standard, negative numbers will be stored in the form of 2’s complement form. In order to get the absolute value, you have to toggle the bits of the number and add 1 to the result. Toggling bit means assigning a bit in its complement value or state. In other words, if the bit is set, then change it to unset and vice versa. To toggle a bit, you can use bitwise XOR operator. This evaluates to 1 if the corresponding bits of both the operands are different; and evaluates to 0 if both the operands are the same.
• Set the value of point as the right shift of an integer by 31 by assuming the integers are stored using 32 bits.

point = p >> 31

• For negative numbers, the points set it as 1 1 1 1 1 1 1 1 and for positive numbers, it will be 0 0 0 0 0 0 0 0. Now add this point to the given number.

point + n

• XOR of point + n and point give the absolute value.

(point + n) ^ point

E.g.:

Output: