Adsense 728 * 15

Search

Custom Search

Find Smallest Number without using Comparison Operator

Write a program in C, C++ to find the smallest number without using comparison operator. The number given is positive integers. Seems tricky, think for some time you'll find the solution.

This a good logical question,  may be it'll asked in interview. Let's solve this problem.

Program to find smallest number in array.

Find second smallest number in array using sorting.

Find Smallest Number without using Comparison Operator

Suppose we have given two numbers and we need to find the smallest element without using the comparison operator.

Logic for solving this problem

Take count variable, run the loop, decrement both the number and increment count variable.

while(a && b){
     a--;
     b--;
     num++;
}

C, C++ Interview Questions.

If any of the number gets zero the loop breaks. Print the num variable. You will get the smallest number without using any comparison operator.


#include <stdio.h>
 
void main()
{
   
   int a,b,num;
   
   printf("Enter two numbers");
   scanf("%d %d",&a,&b);
   
   while(a && b){
       a--;
       b--;
       num++;
   }
   
   printf("Smallest number is %d",num);
}




Find Smallest Number without using Comparison Operator in C++


#include <iostream>
using namespace std;

int main() {

 int a, b, count=0;
 
 cout << "Enter two numbers \n";
 
 /* Taking input */
 cin >> a >> b;
 
 while (a && b)
 {
  a--;
  b--;
  count++;
 }
 
 cout << "The smallest number is " << count;
 
 return 0;
}


Output :

Enter two numbers : 8    2

The smallest number is : 2

1 comment:

  1. Nice one dude. Keep it up. Thanks

    ReplyDelete