Print Smallest Of Three Without Using Comparison Operator in Java

When writing any program, you must be aware of what you’re writing in your code. That way even if you get a pretty easy problem you can add your solution to make it look more creative. Doing so not only enhances your problem-solving skills but also increases creativity levels in you as a programmer. It might feel difficult to do so at first but as you keep solving different questions, you’ll soon be able to add your unique solution different from others. Therefore today we’re going to do the same. We’ll solve the problem of comparisons differently. So let’s find out how to print the Smallest Of Three Integers Without Using Comparison Operator in Java.

 

What’s The Approach?

 

  • Though we can easily find the smallest number, however, the constraint is we cannot use any comparison operators. Therefore we will use subtraction to find the smallest integer.

 

  • Let us consider input Integers x y & z. In a while loop, we’ll pass these Integers as conditions till their value is greater than 0, with & operator. i.e, x != 0 && y != 0 && z != 0.

 

  • Inside the while loop, we’ll decrement each of our input Integers by one. At the same time, we’ll increment a new variable c by one.

 

  • The smallest integer will become 0 first and its value will be the same as variable c, therefore we’ll simply print c as the smallest integer.

 

Also Read: Swap Integers Without Temporary Variable in Java

 

 

 

Java Program To Print Smallest Of Three Integers Without Using Comparison Operator

 

Input:

x = 12

y = 15

z = 5

 

Output:

Minimum of 3 numbers is 5

 

// Java program to find Smallest
// of three integers without
// comparison operators
class TechDecodeTutorials {

    static int smallest(int x, int y, int z)
    {
        int c = 0;

        while (x != 0 && y != 0 && z != 0) {
            x--;
            y--;
            z--;
            c++;
        }

        return c;
    }

    public static void main(String[] args)
    {
        int x = 12, y = 15, z = 5;

        System.out.printf("Minimum of 3"
                            + " numbers is %d",
                        smallest(x, y, z));
    }
}

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *