In this post, we will learn how to find the absolute value of a number using the C++ Programming language.
The absolute value of a number is the actual distance of the integer from zero, in a number line. Therefore, the absolute value is always a positive value and not a negative number.
We will use the following approaches to find the absolute value of a number:
- Using If Statement
- Using abs() Function
So, without further ado, let’s begin this tutorial.
C++ Program to Find the Absolute Value of a Number
// C++ Program to Find the Absolute Value of a Number #include <iostream> using namespace std; int main(){ int n; // Asking for input cout << "Enter an integer: "; cin >> n; // Absolute Value if (n > 0){ cout << "The absolute value of the entered number = " << n << endl; } else{ cout << "The absolute value of the entered number = " << -(n) << endl; } return 0; }
Output 1
Enter an integer: -7
The absolute value of the entered number = 7
Output 2
Enter an integer: 25
The absolute value of the entered number = 25
How Does This Program Work?
int n;
In this program, we have declared an integer data type variable named n.
// Asking for input cout << "Enter an integer: "; cin >> n;
Then, the user is asked to enter an integer.
if (n > 0){ cout << "The absolute value of the entered number = " << n << endl; } else{ cout << "The absolute value of the entered number = " << -(n) << endl; }
Now, we check whether the value of the entered integer is greater than zero or not. If the value is greater, then we print the number as it is as the absolute value.
Otherwise, if the entered number is less than zero then we multiply the value by -1 to get the absolute value.
C++ Program to Find the Absolute Value of a Number Using abs() Function
// C++ Program to Find the Absolute Value of a Number Using abs() Function #include <iostream> #include <cstdlib> using namespace std; int main(){ int n, absolute_value; // Asking for input cout << "Enter an integer: "; cin >> n; // abs() Function absolute_value = abs(n); // Display output cout << "The absolute value of the entered integer is = " << absolute_value << endl; return 0; }
Output
Enter an integer: -47
The absolute value of the entered integer is = 47
Conclusion
I hope after going through this post, you understand how to find the absolute value of a number using the C++ Programming language.
If you have any doubt regarding the program, then contact us in the comment section. We will be delighted to assist you.
Also Read: