Given an integer input, print the Absolute value of the input number
What is Absolute Value?
The absolute value of a number is its distance from zero, regardless of direction. Think of it as "making any number positive" - it removes the negative sign if present!
Simple and Elegant:
#include <iostream>
using namespace std;
int main() {
long long a;
cin >> a;
cout << abs(a); // That's it! ✨
return 0;
}
abs()
is available
in <iostream>
automatically! You don't need <cmath>
.
#include <cmath>
and use fabs()
or abs()
.
// Imagine a number line:
-5 -4 -3 -2 -1 0 1 2 3 4 5
◄────────────────┼────────────────►
// Distance of -5 from 0 = 5 steps
// Distance of +5 from 0 = 5 steps
abs(-5) = 5 // Same distance!
abs(5) = 5
The Logic Behind abs():
// If you were to implement abs() yourself:
int my_abs(int x) {
if (x < 0)
return -x; // Flip the sign
else
return x; // Keep as is
}
// Examples:
// my_abs(-5) → -(-5) → 5 ✓
// my_abs(5) → 5 ✓
// my_abs(0) → 0 ✓
Data Type | Function | Header Required | Example |
---|---|---|---|
int |
abs() |
<iostream> |
abs(-42) → 42 |
long |
labs() or abs() |
<iostream> |
abs(-1000L) → 1000 |
long long |
llabs() or abs() |
<iostream> |
abs(-5LL) → 5 |
float |
fabs() or abs() |
<cmath> |
fabs(-3.14f) → 3.14 |
double |
fabs() or abs() |
<cmath> |
abs(-2.718) → 2.718 |
Where You'll Use Absolute Values:
// Finding temperature change magnitude
int morning_temp = -5; // -5°C
int evening_temp = 10; // 10°C
int change = abs(evening_temp - morning_temp);
// change = abs(10 - (-5)) = abs(15) = 15°C increase
// Or if it drops:
int night_temp = 2;
change = abs(night_temp - evening_temp);
// change = abs(2 - 10) = abs(-8) = 8°C decrease
abs(85) = 85 // Positive stays positive
abs(-5) = 5 // Negative becomes positive
abs(0) = 0 // Zero stays zero
abs(-100000) = 100000 // Large negative
abs(42) = 42 // Already positive
abs()
function is your go-to
tool for finding absolute values. It's simple, efficient, and handles all the
edge cases for you. For detailed exploration of the cmath library and more
mathematical functions, check out Question #21!
abs()
for all types,
so you can just use abs()
instead of remembering
labs()
, llabs()
, or fabs()
!
#include <iostream>
using namespace std;
int main() {
long long a;
cin >> a;
cout << abs(a);
return 0;
}