Compare 2 numbers without using conditionals and built in functions

4.18K viewsProgramming
0

How is it possible to find greater/smaller of 2 numbers without using any conditionals and built in library functions ?

Changed status to publish
0

#include < stdio.h > #define BYTE_SIZE 8
void print(int, int);
   // main function
int main() {
  int a = -21, b = -10;
   print(a, b);
   a = -3;
  b = 0;
  print(a, b);
   a = 345;
  b = 4665;
  print(a, b);
   a = 4;
  b = -67;
  print(a, b);
   a = 0;
  b = 0;
  print(a, b);
   a = 0;
  b = 34;
  print(a, b);
   a = 0;
  b = -56;
  print(a, b);
  return 0;
}
    /* prints out greater/smaller of 2 numbers */
void print(a, b) {
  printf(“Greater of % d and % d is % d\ n”, a, b, greaterNum(a, b));
  printf(“Smaller of % d and % d is % d\ n”, a, b, smallerNum(a, b));
}
    /* find greater of 2 numbers */
int greaterNum(a, b) {
  return (a + b + absVal(a - b)) / 2;
}
    /* find smallers of 2 numbers */
int smallerNum(a, b) {
  return (a + b– absVal(a - b)) / 2;
}
    /* calculate absolute value of a number using bitwise operators*/
int absVal(int x) {
  return (x + (x >> sizeof(x) * BYTE_SIZE– 1)) ^ (x >> sizeof(x) * BYTE_SIZE– 1);
}

Answered question
Write your answer.

Categories