WAP to find difference between two numbers, diff must be Positive
Objective
Write a C++ program to find the absolute positive difference between two numbers.
Algorithm / Approach
- Read two numbers
aandb. - Use a ternary operator to check which number is larger:
diff = (a > b) ? (a - b) : (b - a). - If
ais larger, subtractbfroma. Otherwise, subtractafromb. - Print the calculated positive difference.
main.cpp
#include<iostream>
using namespace std;
int main() {
int a,b,diff;
cout<<"Enter value for A: ";
cin>>a;
cout<<"Enter value for B: ";
cin>>b;
diff = (a>b)?(a-b):(b-a);
cout<<"Diff. = "<< diff;
return 0;
}
Expected Output
Enter Value for A: 10 Enter Value for B: 20 Diff. = 10
Explanation of the Program
- When calculating the difference between two unknown numbers, you run the risk of getting a negative result (e.g., 10 - 20 = -10).
- By using a conditional check (ternary operator) to guarantee we always subtract the smaller number from the larger number, we ensure our result is always a positive Absolute Value.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)