Program to find max(x,y) or Min(x,y) without using any relational and logical operator. Code: int maximum(int x, int y) { int fNum[2],temp,num[2]; num[0] = x; num[1] = y; temp=fNum[ Fun4Sign(x - y)]; return( temp); } int Fun4Sign(int sgn) { int temp; temp= unsigned(sgn) >> (sizeof(int)*8-1); return(temp); } EXTRA DOSE: One More thing to find min and max... Code: int MinimumOf( int a, int b) { return( b + ((a - b) & ((a - b) >> (sizeof(int) * CHAR_BIT - 1))) ); } Code: int MaximumOf( int a, int b) { return( a - ((a - b) & ((a - b) >> (sizeof(int) * CHAR_BIT - 1))) ); }
That's pretty neat, the perhaps not universally portable. Your code does better than just avoiding relational and logical operators, it also avoids conditional (and loop) statements (including ?: ). Here's a re-write: Code: #include <limits.h> /* for CHAR_BIT: number of bits in a char */ #define INT_BITS (sizeof(int) * CHAR_BIT) int maximum( int x, int y ) { int xy[] = { x, y }; return xy[ getSign( x - y )]; /* Index xy by sign of (x-y) */ } int getSign( int n ) { /* Returns sign bit of n */ /* Shift sign into bit position 0 */ return (unsigned)n >> INT_BITS - 1; } One could replace int xy[] = { x, y } by int* xy = &x, but that assumes (minimally) that x has a lower address than y. The method is already making an assumption about manipulating the sign bit that may not work on all computers. I also found your MinimumOf and MaximumOf interesting: Code: /* Fill n with its sign bit, becoming all 1's or 0's */ #define spread_sign(n) ((n) >> (INT_BITS - 1)) /* Return zero if n is positive, otherwise return n */ #define zero_if_positive(n) ((n) & spread_sign(n)) int minimumOf( int a, int b ) { return b + zero_if_positive( a - b ); } int maximumOf( int a, int b ) { return a - zero_if_positive( a - b ); }
Very Very Sorry for this mistake. correct code will be Code: C Code: int maximum(int x, int y) { int fNum[2],temp,num[2]; num[0] = x; num[1] = y; temp=fNum[ Fun4Sign(x - y)]; return( temp); } int Fun4Sign(int sgn) { int temp; temp= unsigned(sgn) >> (sizeof(int)*8-1); return(temp); }
I have updated the above article but learn to use the code block in the posts - [thread=168]Before you make a query[/thread]