Largest Among 3 in C++
Find the largest of three numbers in C++. Use >= so ties don't fall through.
1#include <iostream>2using namespace std;34int main() {5 int a, b, c, largest;67 cout << "Enter three numbers: ";8 cin >> a >> b >> c;910 if (a >= b && a >= c) {11 largest = a;12 } else if (b >= a && b >= c) {13 largest = b;14 } else {15 largest = c;16 }1718 cout << "Largest number is: " << largest << endl;1920 return 0;21}
Output
Enter three numbers: 10 25 15 Largest number is: 25
What's going on
This C++ program finds the largest of three numbers with if / else if. Ties need >=, or two equal maxima fall through to the wrong variable.
cin >> a >> b >> c;
One line can fill all three. Type 10 25 15 and you get the sample output: 25.
if (a >= b && a >= c)
a is a maximum only if it beats (or ties) both others. For 10, 25, 15 this is false.
else if (b >= a && b >= c)
25 >= 10 and 25 >= 15. True. largest = 25.
else
Whatever is left must be c. No extra comparison needed if the first two failed.
Why >= not >: input 10 10 5. With >, the first test is false (10 is not greater than 10), the second is also false, and you print 5. That's the quiet bug.
std::max({a, b, c}) exists in <algorithm>. The if chain is the version you can write when that isn't allowed.
If two values tie for largest, this program reports that value. It does not say which variable it came from.