labs() Function
The labs()
function is declared in the header file <stdlib.h>
.
The labs()
function returns the absolute value of a long integer, ensuring that the result is always non-negative regardless of whether the input is positive or negative. It is the long int version of the abs()
function and is particularly useful when working with large integer values.
Syntax of labs()
long int labs(long int n);
Parameters
Parameter | Description |
---|---|
n | An integral value of type long int for which the absolute value is to be computed. |
It is important to note that the labs()
function operates on long int
values, making it ideal for scenarios where the range of the input exceeds that of the regular abs()
function. This function handles both positive and negative values appropriately, returning a non-negative result.
Return Value
The function returns the absolute value of the provided long integer n
. If n
is negative, the result is its positive counterpart; if n
is non-negative, the result is n
itself.
Examples for labs()
Example 1: Calculating the Absolute Value of a Positive Number
This example demonstrates the use of labs()
with a positive long integer value.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
long int num = 123456789L;
long int result = labs(num);
printf("The absolute value of %ld is %ld.\n", num, result);
return 0;
}
Explanation:
- A
long int
variablenum
is initialized with a positive value. - The
labs()
function is used to compute the absolute value, which in this case is the number itself. - The result is printed using
printf()
.
Program Output:
The absolute value of 123456789 is 123456789.
Example 2: Calculating the Absolute Value of a Negative Number
This example shows how labs()
converts a negative long integer to its positive absolute value.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
long int num = -987654321L;
long int result = labs(num);
printf("The absolute value of %ld is %ld.\n", num, result);
return 0;
}
Explanation:
- A
long int
variablenum
is initialized with a negative value. - The
labs()
function computes the absolute value, converting the negative number to a positive one. - The result is displayed using
printf()
.
Program Output:
The absolute value of -987654321 is 987654321.
Example 3: Handling Zero as Input
This example verifies that the labs()
function correctly handles zero, returning zero as the absolute value.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
long int num = 0L;
long int result = labs(num);
printf("The absolute value of %ld is %ld.\n", num, result);
return 0;
}
Explanation:
- A
long int
variablenum
is set to zero. - The
labs()
function processes the input and returns zero as its absolute value. - The output confirms that the absolute value of zero is zero.
Program Output:
The absolute value of 0 is 0.