C library - abs() function



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

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

Syntax

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

int abs(int x)

Parameters

This function accepts a single parameter −

  • x − It represent an integer value.

Return Value

This function returns the absolute value of an integer.

Example 1

In this example, we create a basic c program to demonstrate the use of abs() function.

#include<stdio.h>
#include<stdlib.h>
int main(){
   int x = -2, res;
   printf("Original value of X is %d\n", x);
   // use the abs() function to get the absolute value
   res = abs(x);
   printf("Absolute value of X is %d", res);
}

Output

Following is the output −

Original value of X is -2
Absolute value of X is 2

Example 2

Let's create another example to get the absolute value of both positive and negative integer. Using the abs() function.

#include<stdio.h>
#include<stdlib.h>
int main(){
   int x, y;
   //absolute of negative number
   x = abs(-10);
   printf("Absolute of -10: %d\n", x);
   // absolute of positive number
   y = abs(12);
   printf("Absolute of 12: %d", y);
}

Output

Following is the output −

Absolute of -10: 10
Absolute of 12: 12

Example 3

Create another c program to get the absolute value of specified integer. Using the abs() function.

#include<stdio.h>
#include<stdlib.h>
int main(){
   int x;
   //absolute of negative number
   x = abs(-10*100);
   printf("Absolute of -10*100: %d\n", x);
}

Output

Following is the output −

Absolute of -10*100: 1000
Advertisements