C++ Program to Find Largest of Three Numbers
if-else statements to compare the numbers and print the largest, for example: if (a >= b && a >= c) cout << a; else if b >= a && b >= c then cout << b; else cout << c;.Examples
How to Think About It
&& (and) operator. If it is greater or equal to both, it is the largest. Otherwise, check the second number similarly. If neither the first nor second is largest, the third must be the largest.Algorithm
Code
#include <iostream> using namespace std; int main() { int a, b, c; cin >> a >> b >> c; if (a >= b && a >= c) cout << a << endl; else if (b >= a && b >= c) cout << b << endl; else cout << c << endl; return 0; }
Dry Run
Let's trace input a=3, b=7, c=5 through the code
Input values
a=3, b=7, c=5
Check if a >= b and a >= c
3 >= 7 is false, so condition fails
Check if b >= a and b >= c
7 >= 3 is true and 7 >= 5 is true, so condition passes
Print b
Output 7
| Step | Condition | Result |
|---|---|---|
| Check a | 3 >= 7 && 3 >= 5 | false |
| Check b | 7 >= 3 && 7 >= 5 | true |
| b | 7 |
Why This Works
Step 1: Compare first number
We use if (a >= b && a >= c) to check if the first number is greater than or equal to both others.
Step 2: Compare second number
If the first check fails, we check b >= a && b >= c to see if the second number is largest.
Step 3: Default to third number
If neither first nor second is largest, the third number must be largest, so we print c.
Alternative Approaches
#include <iostream> #include <algorithm> using namespace std; int main() { int a, b, c; cin >> a >> b >> c; int largest = max(a, max(b, c)); cout << largest << endl; return 0; }
#include <iostream> using namespace std; int main() { int a, b, c; cin >> a >> b >> c; int largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); cout << largest << endl; return 0; }
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of comparisons regardless of input size, so it runs in constant time O(1).
Space Complexity
Only a few variables are used to store inputs and results, so space complexity is O(1).
Which Approach is Fastest?
All approaches run in constant time; using std::max is clean and efficient, while if-else is straightforward and easy to understand.
| Approach | Time | Space | Best For |
|---|---|---|---|
| If-else statements | O(1) | O(1) | Beginners learning basic comparisons |
| std::max function | O(1) | O(1) | Clean and concise code |
| Ternary operator | O(1) | O(1) | Compact code, experienced users |
std::max for a simple and readable way to find the largest number.&& to check both conditions together, causing wrong results.