Search Tutorials

Loading...

Wednesday, 17 April 2013

Find maximum or minimum in two numbers without using if-else

To find the maximum number:
Take a and b two numbers and store in c(another number) than check last bit of c using right shift of 31 bit and AND with 1. it will give last bit of c. If last bit is zero means difference of a and b is positive otherwise negative than use given formula to calculate maximum or minimum number.

Note: Last bit of integer is used for sign. if integer is of 32 bits than 32th bit is used to keep negative or positive sign.

To find maximum number:

#include<stdio.h>
int maximum_number(int a, int b)
{
int c = a - b;
int k = (c >> 31) & 0x1;
int max = a- k * c;
return max;
}

int main()
{
printf("maximum nuber is %d\n",maximum_number(5,10));
getch();
return 0;
}

Output: 

Find-maximum-number
Find maximum number

To find minimum number:

#include<stdio.h>
int minimum_number(int a, int b)
{
int c = a - b;
int k = (c >> 31) & 0x1;
int min = b + k * c;
return min;
}

int main()
{
printf("minimum nuber is %d\n",minimum_number(10,5));
getch();
return 0;
}

Output:

Find-minimum-number
Find minimum number

1 comment:

Back to Top