Print Smallest Of Three Integers Without Comparison Operator in C++
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 C++.
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 awhile
loop, we’ll pass these Integers as conditions till their value is greater than 0, with&
operator. i.e,x && y && z
- 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 C++
C++ 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
// C++ program to find Smallest // of three integers without // comparison operators #include <bits/stdc++.h> using namespace std; int smallest(int x, int y, int z) { int c = 0; while (x && y && z) { x--; y--; z--; c++; } return c; } // Driver Code int main() { int x = 12, y = 15, z = 5; cout << "Minimum of 3 numbers is " << smallest(x, y, z); return 0; }