C library - labs() function



The C stdlib library labs() function is used to returns the absolute value of the long integer number, where absolute represents the positive number.

This function only returns the positive long integer. For example, if we have an long integer value of -45678L, we want to get the absolute number of -45678L. We then used the labs() function to return the positive long number 45678.

Syntax

Following is the C library syntax of the labs() function −

long int labs(long int x)

Parameters

This function accepts a single parameters −

  • X − It represents a long integer value need to be get absolute value.

Return Value

This function returns the absolute value of long integer.

Example 1

Let's create a basic c program to demonstrate the use of labs() function.

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
   long l_num, l_res;
   
   l_num = -45678L;
   l_res = labs(l_num);
   
   printf("The absolute value of %ld is %ld\n", l_num, l_res);
}

Output

Following is the output −

The absolute value of -45678 is 45678

Example 2

Following is the another c program to get the absolute value of both positive and negative long integer. Using the labs() function.

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

int main () {
   long int a,b;

   a = labs(65987L);
   printf("Value of a = %ld\n", a);

   b = labs(-1005090L);
   printf("Value of b = %ld\n", b);
   
   return(0);
}

Output

Following is the output −

Value of a = 65987
Value of b = 1005090

Example 3

Below c program gets the absolute value of specified long integer. Using the labs() function.

#include<stdio.h>
#include<stdlib.h>
int main(){
   long int x;
   //absolute value
   x = labs(-100*5000550);
   printf("Long Absolute of -100*50005550: %ld\n", x);
}

Output

Following is the output −

Long Absolute of -100*50005550: 500055000
Advertisements