abs() function in C
×


abs() function in C

230

The abs() function in C is a standard library function used to compute the absolute value of an integer.

It returns the magnitude of the given integer without its sign.

This function helps in obtaining the positive value of a number, irrespective of its original sign.

Syntax of abs()

int abs(int number);

Parameters:

number: An integer value for which the absolute value is to be calculated.

Return Value:

The abs() function returns the absolute value of the input integer as an integer.

Example:

//prgoram for abs() function in C
#include<stdio.h> 
#include<stdlib.h>

int main() {
    int num = -10;
    int absoluteValue;

    // Calculate absolute value using abs() function
    absoluteValue = abs(num);

    printf("Absolute value of %d is %d\n", num, absoluteValue);

    return 0;
}
	

Output:

Absolute value of -10 is 10

The abs() function is defined in the stdlib.h header file.

It is specifically designed for integers and does not work with floating-point numbers.

For computing the absolute value of floating-point numbers, you should use the fabs() function from the math.h header file.

Using abs() with integers:

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

int main() {
    int num1 = -10;
    int num2 = 20;

    printf("Absolute value of %d: %d\n", num1, abs(num1));
    printf("Absolute value of %d: %d\n", num2, abs(num2));

    return 0;
}

Output:

Absolute value of -10: 10
Absolute value of 20: 20

Using fabs() with floating-point numbers:

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

int main() {
    double num1 = -10.5;
    double num2 = 20.75;

    printf("Absolute value of %.2f: %.2f\n", num1, fabs(num1));
    printf("Absolute value of %.2f: %.2f\n", num2, fabs(num2));

    return 0;
}

Output:

Absolute value of -10.50: 10.50
Absolute value of 20.75: 20.75

For integers, use abs().

For floating-point numbers, use fabs().

Both functions are defined in the stdlib.h header file for integers and the math.h header file for floating-point numbers.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments