Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to find difference between two numbers, diff must be positive

C Code Example — Basic Programs

ADVERTISEMENT

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

  1. Declare variables a, b, and diff.
  2. Read a and b.
  3. Use the ternary operator: diff = (a > b) ? (a - b) : (b - a).
  4. 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 a is greater than b, 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)
ADVERTISEMENT