Spread the love
Write a C program to find the smallest of three integers, without using any of the comparison operators. Let 3 input numbers be x, y and z.
Method 1: – Repeated Subtraction
Take a counter variable c and initialize it with 0. In a loop, repeatedly subtract x, y and z by 1 and increment c. The number which becomes 0 first is the smallest. After the loop terminates, c will hold the minimum of 3.
#include<stdio.h> int smallest(int x, int y, int z) { int c = 0; while ( x && y && z ) { x--; y--; z--; c++; } return c; } int main() { int x = 12, y = 15, z = 5; printf("Minimum of 3 numbers is %d", smallest(x, y, z)); return 0; }
Drawback:- This methid doesn’t work for negative numbers
Method 2: – Use Bit Operations
#include<stdio.h> #define CHAR_BIT 8 /*Function to find minimum of x and y*/ int min(int x, int y) { return y + ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1))); } /* Function to find minimum of 3 numbers x, y and z*/ int smallest(int x, int y, int z) { return min(x, min(y, z)); } int main() { int x = 12, y = 15, z = 5; printf("Minimum of 3 numbers is %d", smallest(x, y, z)); return 0; }
Method 3: – Use Division operator
We can also use division operator to find minimum of two numbers. If value of (a/b) is zero, then b is greater than a, else a is greater
#include <stdio.h> // Using division operator to find minimum of three numbers int smallest(int x, int y, int z) { if (!(y/x)) // Same as "if (y < x)" return (!(y/z))? y : z; return (!(x/z))? x : z; } int main() { int x = 78, y = 88, z = 68; printf("Minimum of 3 numbers is %d", smallest(x, y, z)); return 0; }
If you like this Article, then don’t forget to Click on Social likes buttons.