abs() function in C++

In this guide, you will learn what is abs() function is in C++ programming and how to use it with an example.

1. abs() Function Overview

The abs() function in C++ is used to return the absolute value of an integer. An absolute value is a value that is always non-negative. If the input number is negative, abs() will return its positive counterpart. If the input is non-negative, it will return the number unchanged.

Signature:

int abs(int x);

Parameters:

- x: The integer number whose absolute value is to be found.

2. Source Code Example

#include <iostream>
#include <cstdlib>

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

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

    return 0;
}

Output:

Absolute value of -5 is: 5
Absolute value of 15 is: 15

3. Explanation

1. Two integer numbers num1 and num2 are defined. One is negative, and the other is positive.

2. The abs() function is applied to both numbers.

3. The output displays the absolute values of both numbers. For num1, the function returns the positive counterpart of the negative number. For num2, the function returns the number unchanged as it is already positive.


Comments