What is abs() in C++?
The abs() function in C++ is used to get the absolute value of a number. The absolute value of a number is the distance of the number from 0. In other words, it is the non-negative value of the number. The absolute value of a number x is represented as |x| as shown below:
Library
To use the abs() function, include the following library:
#include <cstdlib>
Declaration
The abs() function is declared as:
int abs(int x);
Or
long int abs(long int x );
Or
long long int abs(long long int x);
x: The number whose absolute value will be calculated.
Return value
The abs() function returns the absolute value of x.
abs() for floating-point types
The abs() function in the cstlib header file computes the absolute value of integer data type i.e. int.
To calculate the absolute value of floating-point types, the abs() function is overloaded in the library cmath. The abs() function in cmath header file is declared as:
double abs (double x);
Or
float abs (float x);
Or
long double abs (long double x);
Or
double abs (T x);
Examples
Example 1
Consider the code snippet below, which demonstrates the use of the abs() function:
#include <cstdlib>#include <iostream>using namespace std;int main(){int x1 = -4;int x2 = 0;int x3 = 4;int abs1 = abs(x1);cout<< "abs ( "<<x1<<" ) = "<<abs1<<endl;int abs2 = abs(x2);cout<< "abs ( "<<x2<<" ) = "<<abs2<<endl;int abs3 = abs(x3);cout<< "abs ( "<<x3<<" ) = "<<abs3<<endl;return 0;}
Explanation
Three integers x1, x2, and x3 are declared in line 8-10. The abs() function is used in line 12, line 15, and line 18 to calculate the absolute value of x1, x2, and x3 respectively.
Example 2
Consider the code snippet below, which demonstrates the use of the abs() function from cmath header file:
#include <cmath>#include <iostream>using namespace std;int main(){float x1 = -4.4;float x2 = 0;float x3 = 4.9;float abs1 = abs(x1);cout<< "abs ( "<<x1<<" ) = "<<abs1<<endl;float abs2 = abs(x2);cout<< "abs ( "<<x2<<" ) = "<<abs2<<endl;float abs3 = abs(x3);cout<< "abs ( "<<x3<<" ) = "<<abs3<<endl;return 0;}
Explanation
Three floats x1, x2, and x3 are declared in line 8-10. The abs() function is used in line 12, line 15, and line 18 to calculate the absolute value of x1, x2, and x3 respectively.
Free Resources