fabs() Function Example in C Programming

In this source code example, we will see how to use the fabs() function in C programming with an example.

fabs() Function Overview

The fabs() function in C returns the absolute value of a floating-point number. In other words, it converts negative values to positive, and positive values remain unchanged. 

This function is indispensable when comparing magnitudes without considering the sign or when calculating distances. It's housed in the math.h library. 

 Key Points: 

- The math.h header is required to use the fabs() function. 

- It converts negative floating-point numbers to their positive counterparts; positive numbers remain unaffected. 

- Always remember to link the math library using the -lm flag when compiling.

Source Code Example

#include <stdio.h>
#include <math.h>  // Necessary for fabs()

int main() {
    double value, result;

    // Prompt user for input
    printf("Enter a floating-point value: ");
    scanf("%lf", &value);

    // Use the fabs() function to obtain the absolute value
    result = fabs(value);

    // Display the absolute value
    printf("The absolute value of %.2lf is: %.2lf\n", value, result);

    return 0;
}

Output

Enter a floating-point value: -3.14
The absolute value of -3.14 is: 3.14

Explanation

1. We initiate by incorporating the essential header files: stdio.h for input/output operations and math.h for the fabs() function.

2. In the main() function, we request the user to provide a floating-point value.

3. The fabs() function is then used to calculate the absolute value of the input.

4. The computed absolute value is subsequently displayed on the console.


Comments