fabs() Function

The fabs() function in C computes the absolute value of a given number, effectively returning its non-negative counterpart regardless of its original sign.


Syntax of fabs()

</>
Copy
double fabs(double x);
float fabsf(float x);
long double fabsl(long double x);

Parameters

ParameterDescription
xThe number whose absolute value is to be computed.

The function evaluates the magnitude of the input and returns its absolute value. This is particularly useful for mathematical computations where only the size of a number matters, regardless of its sign.

Return Value

The function returns the absolute value of the provided number.


Examples for fabs()

Example 1: Using fabs() with a Positive Number

This example demonstrates how fabs() works when the input is already positive.

Program

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

int main() {
    double num = 42.7;
    double result = fabs(num);

    printf("The absolute value of %.2f is %.2f\n", num, result);
    return 0;
}

Explanation:

  1. A double variable num is initialized with the positive value 42.7.
  2. The fabs() function computes its absolute value, which remains 42.7.
  3. The result is printed, showing that the absolute value is unchanged for positive numbers.

Program Output:

The absolute value of 42.70 is 42.70

Example 2: Using fabs() with a Negative Number

This example demonstrates how fabs() converts a negative number into its positive equivalent.

Program

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

int main() {
    double num = -15.3;
    double result = fabs(num);

    printf("The absolute value of %.2f is %.2f\n", num, result);
    return 0;
}

Explanation:

  1. A double variable num is initialized with a negative value -15.3.
  2. The fabs() function computes the absolute value, resulting in 15.3.
  3. The output confirms that the negative number has been converted to a positive value.

Program Output:

The absolute value of -15.30 is 15.30

Example 3: Using fabsf() for Float Values

This example demonstrates the usage of fabsf() to compute the absolute value of a float number.

Program

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

int main() {
    float num = -3.14f;
    float result = fabsf(num);

    printf("The absolute value of %.2f is %.2f\n", num, result);
    return 0;
}

Explanation:

  1. A float variable num is initialized with the negative value -3.14f.
  2. The fabsf() function calculates its absolute value, which is 3.14f.
  3. The result is printed, confirming the function’s ability to handle float types.

Program Output:

The absolute value of -3.14 is 3.14