← Back

21. Absolute Difference of Two Integers

Easy

📝 Problem

Get two integers from user and print the absolute difference between two integers.

Input Format:
Accept two integers as input
Output Format:
Print the absolute difference
Constraints:
1 ≤ N1, N2 ≤ 10^9
Sample Input 1:
78 25
Sample Output 1:
53
Sample Input 2:
10 20
Sample Output 2:
10
🎯 Understanding the abs() Function - Your First Math Library!

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!

💡 What is abs()?
The 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++.

1️⃣ The <cmath> Library

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

2️⃣ How abs() Works

📌 Visual Example:
// 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

3️⃣ Important: abs() vs abs() - Type Matters!

⚠️ Pro Tip: C++ has different abs functions for different types:
  • 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!

4️⃣ Real-World Applications

Absolute difference is used in:

  • Distance calculations - Finding the gap between two points
  • Error measurements - Comparing predicted vs actual values
  • Temperature changes - Calculating temperature drops/rises
  • Financial analysis - Computing price differences
🚀 Try This Challenge!
After solving this problem, try modifying the code to also print which number is larger along with the difference. This will help you practice conditional statements!
💻 Solution Code
#include <iostream>
#include <cmath>

using namespace std;

int main() {
    int a, b;
    cin >> a >> b;
    cout << abs(a - b);
    return 0;
}