Middle of three using minimum comparisons in C++


In this section, we will see how to find the middle of three given values by comparing them. So if three numbers are given like (10, 30, 20), then it will find 20 as this is the middle element. Let us see the algorithm first, then we will implement that algorithm into C++ code.

Algorithm

middle_of_three(a, b, c):
Input: Three numbers a, b and c
Output: The middle of these three
Begin
   if a > b, then
      if b > c, then
         return b
      else if a > c, then
         return c
      else
         return a
      else
         if a > c, then
            return a
         else if b > c, then
            return c
      else
         return b
End

Example

#include <iostream>
using namespace std;
int mid_three(int a, int b, int c) {
   if (a > b) {
      if (b > c)
         return b;
      else if (a > c)
         return c;
      else
         return a;
   } else {
      if (a > c)
         return a;
      else if (b > c)
         return c;
      else
         return b;
   }
}
main() {
   int a = 10, b = 30, c = 20;
   cout << "Middle Out of Three "<< mid_three(a, b, c);
}

Output

Middle Out of Three 20

Updated on: 30-Jul-2019

458 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements