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()

</>
Copy
long int labs(long int n);

Parameters

ParameterDescription
nAn 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

</>
Copy
#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:

  1. A long int variable num is initialized with a positive value.
  2. The labs() function is used to compute the absolute value, which in this case is the number itself.
  3. 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

</>
Copy
#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:

  1. A long int variable num is initialized with a negative value.
  2. The labs() function computes the absolute value, converting the negative number to a positive one.
  3. 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

</>
Copy
#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:

  1. A long int variable num is set to zero.
  2. The labs() function processes the input and returns zero as its absolute value.
  3. The output confirms that the absolute value of zero is zero.

Program Output:

The absolute value of 0 is 0.