Median of Three
Programming Basics · C++
TASK
Problem
Given three integers `a`, `b`, and `c`, print their median: the value that would be in the middle after sorting.
EXAMPLE
Example
1 2 3
2
LIMITS
Constraints
|a|, |b|, |c| ≤ 10^9.
LEARN
Theory for this problem
+
An `if` / `else if` / `else` chain checks alternatives from top to bottom. Put more specific or higher-priority conditions first.
Connection to “Median of Three”: here, intermediate values are best kept in named variables so the formula stays readable and data types remain clear.
NEED HELP?
Hints
+
['List the possible cases and make them mutually exclusive.', 'After solving “Median of Three”, verify the algorithm on your own small example and on an allowed boundary case. Print only the required result with no extra text.']
ANSWER
Solution
+
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
long long a, b, c;
cin >> a >> b >> c;
long long mn = min(a, min(b, c));
long long mx = max(a, max(b, c));
cout << a + b + c - mn - mx << '\n';
return 0;
}