c++ absolute value

To calculate the absolute value of a number in C++, you can use the abs() function from the <cmath> library. Here are the steps to do so:

  1. Include the <cmath> library:
#include <cmath>

This line at the beginning of your code includes the <cmath> library, which provides various mathematical functions, including the abs() function.

  1. Declare a variable to store the number:
int num = -5;

This line declares an integer variable num and assigns it a value of -5. You can replace -5 with any number for which you want to calculate the absolute value.

  1. Use the abs() function to calculate the absolute value:
int absValue = std::abs(num);

This line uses the abs() function from the <cmath> library to calculate the absolute value of num. The result is stored in the variable absValue.

  1. Print the absolute value:
std::cout << "Absolute value: " << absValue << std::endl;

This line prints the absolute value stored in the variable absValue using the std::cout stream.

Here's the complete code:

#include <iostream>
#include <cmath>

int main() {
    int num = -5;
    int absValue = std::abs(num);
    std::cout << "Absolute value: " << absValue << std::endl;

    return 0;
}

When you run this code, it will output:

Absolute value: 5

This indicates that the absolute value of -5 is 5.