Abs Function In C++ Code

3 min read Jun 28, 2024
Abs Function In C++ Code

The abs() Function in C++

The abs() function in C++ is used to calculate the absolute value of an integer. It takes a single integer argument and returns the absolute value of that integer. The absolute value of an integer is its distance from zero, regardless of its sign.

Here's a breakdown of the abs() function:

Syntax:

int abs(int n);

Parameters:

  • n: An integer whose absolute value needs to be calculated.

Return Value:

  • int: The absolute value of the input integer.

How it works:

The abs() function works by simply removing the sign of the input integer. If the input is positive, it returns the same value. If the input is negative, it returns the positive equivalent.

Example:

#include 
#include 

using namespace std;

int main() {
  int num1 = 5;
  int num2 = -10;

  cout << "Absolute value of " << num1 << " is: " << abs(num1) << endl;
  cout << "Absolute value of " << num2 << " is: " << abs(num2) << endl;

  return 0;
}

Output:

Absolute value of 5 is: 5
Absolute value of -10 is: 10

Note:

The abs() function is defined in the <cstdlib> header file. You need to include this header file in your program to use it.

Other Absolute Value Functions:

  • labs(): For long integers.
  • llabs(): For long long integers.
  • fabs(): For floating-point numbers.

These functions are also defined in <cstdlib>, and they work in the same way as abs(), but they handle different data types.

Key Points:

  • abs() is a built-in function for calculating absolute values.
  • It takes an integer as input and returns its absolute value.
  • It is defined in the <cstdlib> header file.
  • There are similar functions available for long integers, long long integers, and floating-point numbers.

By understanding the abs() function, you can easily calculate absolute values in your C++ programs, making your code more efficient and readable.