How to Write a C program to find the smallest of three integers, without using any of the comparision operators.?
Smallest of 3 numbers without using Comparator operator.
Collapse
X
-
Tags: None
-
Why do you want to do that? Is it a riddle from your textbook? If so, this is notOriginally posted by Nethra NayakHow to Write a C program to find the smallest of three integers, without using any of the comparision operators.?
a do-my-homework service; first give it a try yourself.
kind regards,
Jos (moderator)
hint: check whether or not the sign bit of (a-b) is set. -
As I wrote before: use the sign bit of an expression. Something like this:
LESS(x, y) will be true (not 0) when x < y. This trickery-dickery only works forCode:#define ALL ((unsigned int)~0) #define SGN (ALL^(ALL>>1)) #define LESS(X,Y) (((X)-(Y))&SGN)
ints.
kind regards,
JosComment
-
Gannon11 says:
Yes, but to determine which result was smallest, you'd have to use...a comparison operator.
Why couldn't the 3 products be printed out as shown and then
cout<<"Which int: ";
cin>>numsmall;
user chooses n1 or n2 or n3 on the basis of which n is common to two smallest products
cout<<"The smallest int is: "<<numsmall ;
QED but agreed <<<<<< than elegantComment
-
Alan Lopez
Let your three integers be:
int num1, num2, num3;
//starts computing smallest number
if ( num1 < num2 ) {
if ( num1 < num3 ) {
printf( "Smallest if is %d\n", num1 );
}
}
if ( num2 < num1 ) {
if ( num2 < num3 ) {
printf( "Smallest if is %d\n", num2 );
}
}
if ( num3 < num1 ) {
if ( num3 < num2 ) {
printf( "Smallest if is %d\n", num3 );
}
}Comment
Comment