abs() Function

The abs() function in C computes the absolute value of an integer, effectively returning its magnitude without regard to its sign. This function is part of the C Standard Library and is declared in stdlib.h.


Syntax of abs()

</>
Copy
int abs(int n);

Parameters

ParameterDescription
nAn integral value whose absolute value is to be computed.

Return Value

The function returns the absolute value of the provided integer.

It is important to note that in C, abs() works exclusively with integer values. Although C++ provides overloaded versions for floating-point numbers, complex numbers, and valarrays, the C implementation only handles integers.


Examples for abs()

Example 1: Calculating the Absolute Value of a Positive Integer

This example shows how abs() returns the same value when the input is already positive.

Program

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

int main() {
    int value = 42;
    int result = abs(value);

    printf("The absolute value of %d is %d\n", value, result);
    return 0;
}

Explanation:

  1. An integer variable is assigned the positive value 42.
  2. The abs() function computes the absolute value, which remains 42.
  3. The result is printed to the console.

Output:

The absolute value of 42 is 42

Example 2: Calculating the Absolute Value of a Negative Integer

This example demonstrates how abs() converts a negative integer to its positive equivalent.

Program

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

int main() {
    int value = -17;
    int result = abs(value);

    printf("The absolute value of %d is %d\n", value, result);
    return 0;
}

Explanation:

  1. An integer variable is assigned the negative value -17.
  2. The abs() function converts -17 to its absolute value, 17.
  3. The result is displayed using printf().

Output:

The absolute value of -17 is 17