Java Program to find difference between two numbers, diff must be Positive.
Objective
Write a Java program to find the positive difference between two numbers.
Algorithm / Approach
- Take two numbers as input.
- Use the ternary operator to check which number is larger.
- If
x > y, subtractyfromx; otherwise, subtractxfromy. - Print the positive difference.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Num1: ");
int x = s.nextInt();
System.out.print("Enter Num2: ");
int y = s.nextInt();
int r = (x>y)?(x-y):(y-x);
System.out.print("Diff. = "+r);
}
}
Expected Output
Enter Num1: 12 Enter Num2: 15 Diff. = 3
Explanation of the Program
- Two numbers,
xandy, are evaluated. - The program uses the ternary operator
(x > y) ? (x - y) : (y - x). - This ensures the smaller number is always subtracted from the larger one, guaranteeing a positive difference.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Simply returning
x - y, which can result in a negative difference.