Get two integers from user and print the absolute difference between two integers.
Why We Need abs()
When calculating the difference between two numbers, the order matters:
78 - 25 = 53
, but 25 - 78 = -53
.
The absolute difference always gives us a positive result, regardless of order!
abs()
function returns the absolute value (magnitude without sign) of a number.
It's part of the <cmath>
library, which provides mathematical functions in C++.
The <cmath>
library is your toolbox for mathematical operations:
Function | Purpose | Example |
---|---|---|
abs(x) |
Absolute value | abs(-5) → 5 |
sqrt(x) |
Square root | sqrt(16) → 4 |
pow(x, y) |
Power (x^y) | pow(2, 3) → 8 |
ceil(x) |
Round up | ceil(4.2) → 5 |
floor(x) |
Round down | floor(4.8) → 4 |
// Input: 78 25
int a = 78, b = 25;
// Method 1: Manual calculation (wrong if b > a)
int diff = a - b; // 53 ✓ (works)
// What if a = 25, b = 78?
diff = a - b; // -53 ✗ (negative!)
// Method 2: Using abs() (always correct!)
int diff = abs(a - b); // Always positive!
// Works for both: abs(78-25)=53 and abs(25-78)=53
abs(int)
- From <cstdlib>
(for integers)fabs(double)
- From <cmath>
(for floating-point)labs(long)
- From <cstdlib>
(for long integers)
For this problem with integers, abs()
works perfectly. Including
<cmath>
gives you access to all mathematical functions at once!
Absolute difference is used in:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
cout << abs(a - b);
return 0;
}