Usage of the Abs Function in C Language

The abs() function is a mathematical function used in C language to compute the absolute value of any integer. Its prototype is: int abs(int x); where x is any integer. The return value of the function is the absolute value of x, which means its positive equivalent. If x is positive, the result will be x itself; if x is negative, the result will be -x. It’s important to note that the abs() function only applies to integers; for calculating absolute values of floating-point numbers, other functions like fabs() should be used.

Here’s a simple example: #include <stdio.h> #include <stdlib.h> int main() { int a = 10, b = -5, c = 0; printf("abs(a) = %d ", abs(a)); printf("abs(b) = %d ", abs(b)); printf("abs(c) = %d ", abs(c)); return 0; }

The output will be: ab(a) = 10 ab(b) = 5 ab(c) = 0 From this output, we can see that the abs() function correctly calculates the absolute values for any positive number, negative number, and zero.

Leave a Reply

Your email address will not be published. Required fields are marked *