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.
Don’t get amazed, there is a simple mathematical logic behind it which I will explain step by step.
(big + small) + (big - small)
By performing above calculation we will get a number that is twice the bigger one.
[adsense1]
Here is the implementation of above process in the program.
/*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
(big + small) - (big - small)
By performing above calculation we will get a number that is twice the smaller one.
Now let’s see how it is implemented in the program.
/*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
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.