Beginner · conditionals
Maximum of Three
Read three integers and print the largest. Sounds trivial — until the judge feeds you negatives, duplicates and all-equal inputs. The lesson is in the edge cases.
At a glanceRead three integers and print the largest with nested if/else or a running max; the hidden tests include negatives, duplicates and all-equal values, so starting the max at 0 fails.
Problem
Input: one line with three integers a, b, c.
Output: the largest of the three.
Samples:
| Input | Output |
|---|---|
3 7 5 | 7 |
-1 -5 -3 | -1 |
Your solution
Custom input for "Run my input"
Judging runs in your browser against hidden tests. A runaway loop is cut off after 3 seconds — still, make sure every loop has an exit. Your code is saved in this browser as you type.
Stuck? Hints
Hint 1 — the running-maximum pattern
Don't compare all three at once. Assume the first is the max: int m = a; then improve it: if (b > m) m = b; and if (c > m) m = c;. Two simple comparisons beat a tangle of nested if/else — and the same pattern scales to finding the max of a whole array.
Hint 2 — why negatives break naive solutions
If you start with int m = 0; and take maxes, input -1 -5 -3 wrongly prints 0. Always seed the maximum with an actual value from the input, never a made-up constant.
Solution (try it first!)
#include <iostream>
using namespace std;
int main() {
int a, b, c;
cin >> a >> b >> c;
int m = a;
if (b > m) m = b;
if (c > m) m = c;
cout << m << endl;
return 0;
}
Duplicates and all-equal inputs work for free here — > keeps the current max when values tie. The running-maximum pattern is the same one used in the loop article's accumulator; next, meet its while-loop cousin in Count the Digits.
Deep dive
Why this works
A running maximum (best = max(best, x)) scales to any number of inputs; a three-way if/else tree does not. Prefer the shape that generalises.
The cost
O(1) either way — three comparisons. The cost difference is zero; the maintenance difference is not.
Where it goes wrong
if (a > b) if (a > c)mishandles ties and the case where a is smallest. Compare against a running best instead.- Initialising
best = 0breaks on all-negative input. Seed it with a real value from the input.
Next step
The same idea over a whole array: Array Maximum.
Two things to remember
- Running best beats a decision tree — it generalises.
- Seed a maximum with real data, never with 0.
🐞 This version fails — open it and try
Seeds the maximum with 0, so all-negative input fails
#include <iostream>
using namespace std;
int main() {
int a, b, c;
cin >> a >> b >> c;
int best = 0;
if (a > best) best = a;
if (b > best) best = b;
if (c > best) best = c;
cout << best << endl;
return 0;
}