C program to compare two numbers without using relational operators


In this example, you will learn the simple logic behind C program to compare two numbers without using relational operators and its implementation in C program.

C program to compare two numbers without using relational operators

Don’t get amazed, there is a simple mathematical logic behind it which I will explain step by step.

How to find greater number among two without using relational operator in C?

  • Add sum and difference of two numbers. This will cancel the effects of smallest number
(big + small) + (big - small)

By performing above calculation we will get a number that is twice the bigger one.

  • Now divide the number by 2 to get the original number.

Here is the implementation of above process in the program.

C program to find greater number without using relational operator

/*C program to find greater out of two
numbers without using comparison*/

#include<stdio.h>
#include<math.h>

int main()
{
   int x, y;
   printf("Enter two numbers:\n");
   scanf("%d %d", &x, &y);

   //finding largest number between two
   printf("\nLargest number: %d\n", ((x + y) + abs(x - y)) / 2);

   return 0;
}

Output

greater output

How to find smaller number among two without using relational operator in C?

  • Subtract the sum and difference of two numbers. This will cancel the effects of largest number
(big + small) - (big - small)

By performing above calculation we will get a number that is twice the smaller one.

  • Now divide the number by 2 to get the original number.

Now let’s see how it is implemented in the program.

C program to find out smaller number without using relational operator

/*C program to find smaller out of two
numbers without using comparison*/

#include<stdio.h>
#include<math.h>

int main()
{
   int x, y;
   printf("Enter two numbers:\n");
   scanf("%d %d", &x, &y);

   //finding smaller number between two
   printf("\nSmallest number: %d\n", ((x + y) - abs(x - y)) / 2);

   return 0;
}

Output

smallest output

Explanation
In both programs, we have used math.h header file for using standard abs( ) math library function. This function is used for using absolute value i.e. positive values only.