w3resource

C Language: Custom abs() function

C - Implementing a custom abs() function

The abs() function is used to compute the absolute value of an integer value.
Here's an example of how to implement a custom abs() function:

Code:

#include <stdio.h>

int custom_abs(int n) {
    return (n < 0) ? -n : n;
}
int main() {
    int x = 100, y = -100;
    printf("Value of x = %d and y = %d", x, y);
    printf("\nAbsolute Value of x = %d and y = %d", custom_abs(x), custom_abs(y));    
    return 0;
}

Output:

Value of x = 100 and y = -100
Absolute Value of x = 100 and y = 100


Follow us on Facebook and Twitter for latest update.