The abs()
Function in C++ Header File
The abs()
function in C++ is used to calculate the absolute value of an integer. It is defined in the <cstdlib>
header file.
Definition and Usage
The syntax of the abs()
function is as follows:
int abs(int n);
The function takes a single integer argument n
and returns the absolute value of n
. The absolute value of a number is its distance from zero, regardless of its sign.
Here's a breakdown of how the function works:
- If
n
is a positive number, the function returnsn
. - If
n
is a negative number, the function returns-n
. - If
n
is zero, the function returns zero.
Example
Here's an example of how to use the abs()
function:
#include
#include
int main() {
int number = -5;
int absoluteValue = abs(number);
std::cout << "The absolute value of " << number << " is: " << absoluteValue << std::endl;
return 0;
}
This program will print the following output:
The absolute value of -5 is: 5
Note
The abs()
function works only for integer values. If you need to calculate the absolute value of a floating-point number, you can use the fabs()
function, which is also defined in the <cstdlib>
header file.
Conclusion
The abs()
function is a simple and useful function for calculating absolute values in C++. It is a part of the standard library and can be easily used in your programs.