Math Abs Function - C++ Programming Tutorial
C++ Course / Math Functions / Math Abs Function

Math Abs Function

BLUF: Mastering Math Abs Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Math Abs Function

C++ is renowned for its efficiency. Learn how Math Abs Function enables low-level control and high-performance computing in the tutorial below.

C++ Math abs

The function calculates the absolute value of a specified number.

Suppose a number is 'x' :

Example

abs(x) = |x|;

Difference between abs and fabs

The abs function does not accept arguments of float or double types, whereas the fabs function can handle arguments of float, double, and integer types.

Syntax

Example

int abs( int x);
long int abs(long int x );
 long long int abs(long long int x);

Parameter

x : The value for which the absolute value needs to be calculated.

Return value

It returns the absolute value of x.

Example 1

Let's examine a basic scenario where the value of x is below zero.

Example

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
    int x= -9;
    std::cout << "Value of x is :" <<x<< std::endl;
    cout<<"Absolute value of x is : "<<abs(x);

    
   return 0;
}

Output:

Output

Value of x is :-9
Absolute value of x is : 9

In this instance, the abs function calculates the absolute value of x and provides a result of 9.

Example 2

Let's consider a straightforward scenario where the value of x is greater than zero.

Example

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
   int x= 89;
  std::cout << "Value of x is :" <<x<< std::endl;
 cout<<"Absolute value of x is : "<<abs(x);
return 0;
}

Output:

Output

Value of x is :89
Absolute value of x is : 89

In this instance, the abs function calculates the absolute value of x.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience