Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to find difference between two numbers, diff must be Positive

C++ Code Example — Basic Programs

ADVERTISEMENT

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

  1. Read two numbers a and b.
  2. Use a ternary operator to check which number is larger: diff = (a > b) ? (a - b) : (b - a).
  3. If a is larger, subtract b from a. Otherwise, subtract a from b.
  4. 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)
ADVERTISEMENT