C Program to find difference between two numbers, diff must be positive
Objective
Write a C program to find the absolute positive difference between two numbers using the ternary operator.
Algorithm / Approach
- Declare variables
a,b, anddiff. - Read
aandb. - Use the ternary operator:
diff = (a > b) ? (a - b) : (b - a). - Print the difference.
main.c
#include<stdio.h>
int main( ) {
int a, b, diff;
printf("Enter Values for A : ");
scanf("%d",&a);
printf("Enter Values for B : ");
scanf("%d",&b);
diff = (a>b) ? a-b : b-a;
printf("DIFFERENCE IS : %d\n",diff);
return 0;
}
Expected Output
Enter Values for A : 62 Enter Values for A : 95 DIFFERENCE IS : 33
Explanation of the Program
- The Ternary Operator (
? :) is a shorthand for an if-else statement. - The syntax is
(Condition) ? True_Value : False_Value. - In this program, if
ais greater thanb, we subtract b from a. If it is false, we subtract a from b. This guarantees that the result is always a positive number (acting exactly like the mathematical absolute value function).
Complexity
Time Complexity
O(1)
Space Complexity
O(1)