QUESTION #025

Find Largest of Four Numbers

Easy

📋 Problem Statement

Find the largest value among four given numbers.

🎯 Scaling Up: From 3 to 4 Numbers

When dealing with more than three values, manual if-else logic becomes complex. This is where nested max() functions or initializer lists shine:

  • Nested Approach: Break the problem into smaller comparisons
  • Step-by-step: Compare pairs, then compare results
  • Modern C++: Use initializer list for clean, scalable code
  • Temporary Variables: Store intermediate results for clarity
Nested Max Strategy: Progressive Reduction
Numbers:  a = 10,  b = 30,  c = 20,  d = 25

Step 1: Find max of first pair
        temp = max(a, b)
        temp = max(10, 30) = 30

Step 2: Compare temp with c
        result = max(temp, c)
        result = max(30, 20) = 30

Step 3: Compare result with d
        maximum = max(result, d)
        maximum = max(30, 25) = 30

Final Result: Largest is 30

📥 Input Format

Accept four integers as input

📤 Output Format

Print the output as "Largest is ___"

💡 Examples

Example 1:
Input: 10 30 20 25
Output: Largest is 30
Step-by-step Analysis:
• Numbers: a=10, b=30, c=20, d=25
• Step 1: max(10, 30) = 30
• Step 2: max(30, 20) = 30
• Step 3: max(30, 25) = 30
Result: Largest is 30
Example 2:
Input: 100 50 200 75
Output: Largest is 200
Step-by-step Analysis:
• Numbers: a=100, b=50, c=200, d=75
• Step 1: max(100, 50) = 100
• Step 2: max(100, 200) = 200
• Step 3: max(200, 75) = 200
Result: Largest is 200 (third value is maximum)
Example 3:
Input: 5 5 5 5
Output: Largest is 5
Step-by-step Analysis:
• All values are equal
• Step 1: max(5, 5) = 5
• Step 2: max(5, 5) = 5
• Step 3: max(5, 5) = 5
Result: Works correctly for equal values
Example 4 (Negative Numbers):
Input: -10 -5 -20 -15
Output: Largest is -5
Step-by-step Analysis:
• Numbers: a=-10, b=-5, c=-20, d=-15
• Remember: -5 is larger than all others
• Step 1: max(-10, -5) = -5
• Step 2: max(-5, -20) = -5
• Step 3: max(-5, -15) = -5
Result: Largest is -5
Example 5 (Maximum at End):
Input: 15 20 18 50
Output: Largest is 50
Step-by-step Analysis:
• The largest value is in the last position
• Step 1: max(15, 20) = 20
• Step 2: max(20, 18) = 20
• Step 3: max(20, 50) = 50
Result: Final comparison reveals the maximum

⚠️ Constraints

-10^15 <= INPUT <= 10^15

✅ Solution

#include <iostream>
#include <algorithm>

using namespace std;

int main() {
    long long a, b, c, d, maximum, temp;
    cin >> a >> b >> c >> d;
    
    // Step 1: Find max of first two numbers
    temp = max(a, b);
    
    // Step 2: Find max of all four using nested max()
    maximum = max(max(temp, c), d);
    
    // Alternative: Use initializer list (C++11 and later)
    // maximum = max({a, b, c, d});  // Cleaner and more scalable
    
    cout << "Largest is " << maximum;
    
    return 0;
}

🔑 Key Concepts

  • Nested max() Functions: Breaking down complex comparisons into steps
  • Temporary Variables: Using temp to store intermediate results
  • Progressive Reduction: Reducing 4 values → 2 values → 1 value
  • Scalability: Understanding when manual logic becomes impractical
  • Initializer Lists: Modern C++ approach for multiple values
  • Algorithm Header: Required for max() function

💡 Understanding Nested max() Functions

Breaking Down the Solution:

// Given: a=10, b=30, c=20, d=25

// Method shown in solution:
temp = max(a, b);              // temp = max(10, 30) = 30
maximum = max(max(temp, c), d);  // max(max(30, 20), 25)
                                    //     max(30, 25) = 30

Step-by-Step Evaluation:

  1. temp = max(a, b) → Compare first two values, store result
  2. max(temp, c) → Compare stored result with third value
  3. max(previous_result, d) → Compare with fourth value
  4. Final result is the maximum of all four

Alternative Without temp Variable:

// Single line - deeply nested
maximum = max(max(max(a, b), c), d);

// Reads from inside out:
// 1. max(a, b) - innermost
// 2. max(result, c) - middle
// 3. max(result, d) - outermost

🚀 Modern C++11 Approach: Initializer List

The cleanest and most scalable solution uses an initializer list:

#include <iostream>
#include <algorithm>

using namespace std;

int main() {
    long long a, b, c, d;
    cin >> a >> b >> c >> d;
    
    // One-line solution with initializer list
    long long maximum = max({a, b, c, d});
    
    cout << "Largest is " << maximum;
    
    return 0;
}

Advantages of Initializer List:

  • Cleaner Code: Single line, easy to read
  • Scalable: Easy to add more values: max({a, b, c, d, e, f})
  • Less Error-Prone: No complex nesting to maintain
  • Modern Standard: Idiomatic C++11+ code
  • ⚠️ Requires C++11: Compile with -std=c++11 or later

⚖️ Comparison of All Methods

Method Code Complexity Readability Scalability Best For
Manual If-Else Very High (16+ conditions) Poor ❌ Not scalable Learning only
Nested max() with temp Low Good ⚠️ Moderate Understanding steps
Nested max() single line Low Fair ⚠️ Gets complex Compact code
Initializer List Very Low Excellent ✅ Highly scalable Production code
Loop with Array Low Excellent ✅ Infinitely scalable Many values

⚠️ Why Manual If-Else Becomes Impractical

For 4 numbers, manual comparison requires checking many cases:

// ❌ NOT RECOMMENDED: Too complex and error-prone!
if (a > b && a > c && a > d)
    maximum = a;
else if (b > a && b > c && b > d)
    maximum = b;
else if (c > a && c > b && c > d)
    maximum = c;
else
    maximum = d;

// This only works if no values are equal!
// Edge cases with equal values would need more conditions!

Problems with this approach:

  • ❌ Doesn't handle equal values correctly
  • ❌ 12 individual comparisons (a>b, a>c, a>d, etc.)
  • ❌ Very error-prone to write and maintain
  • ❌ Doesn't scale - 5 numbers would be even worse!

Key Lesson: This is exactly why we use library functions like max() - they handle all edge cases correctly and make code readable!

🎯 Most Scalable: Loop with Array

For ultimate flexibility, use an array and loop:

#include <iostream>

using namespace std;

int main() {
    long long numbers[4];
    
    // Read all four numbers
    for (int i = 0; i < 4; i++) {
        cin >> numbers[i];
    }
    
    // Find maximum using loop
    long long maximum = numbers[0];
    for (int i = 1; i < 4; i++) {
        if (numbers[i] > maximum) {
            maximum = numbers[i];
        }
    }
    
    cout << "Largest is " << maximum;
    
    return 0;
}

Benefits:

  • ✅ Works for any number of values (just change array size and loop limit)
  • ✅ Easy to understand and maintain
  • ✅ Can be extended to find position, count occurrences, etc.
  • ✅ Foundation for more advanced algorithms

🌍 Real-world Applications

  • Gaming: Finding highest score among 4 players
  • Sports: Determining winner among 4 competitors
  • Finance: Comparing quarterly performance (4 quarters)
  • Image Processing: Finding maximum value in 2x2 pixel blocks
  • Sensor Networks: Maximum reading from 4 sensors
  • Database Queries: Finding maximum among multiple columns
  • E-commerce: Highest price among 4 sellers
  • Weather Systems: Maximum temperature among 4 stations

🎯 What You'll Learn

  • Understanding when manual logic becomes impractical
  • Using nested function calls effectively
  • Working with temporary variables for clarity
  • Modern C++11 initializer list syntax
  • Choosing the right approach for the problem scale
  • Understanding scalability in algorithm design
  • Reading and writing nested function calls
  • Importance of using standard library functions

💪 Extension Challenges

  • Level 1: Find both largest and smallest of 4 numbers
  • Level 2: Find the second largest among 4 numbers
  • Level 3: Find largest of 5 or 6 numbers
  • Level 4: Sort all 4 numbers in descending order
  • Level 5: Find which position (1st, 2nd, 3rd, or 4th input) had the largest value
  • Level 6: Calculate range (difference between max and min)
  • Level 7: Find largest of N numbers (user inputs N, then N values)
  • Bonus: Implement all three methods and compare their readability

💡 Practice Tips

  • Try All Methods: Implement using temp variable, single line, and initializer list
  • Test Edge Cases: All equal (5,5,5,5), all different, two pairs equal
  • Test Positions: Maximum at start, middle, end positions
  • Negative Numbers: (-10, -5, -20, -15), (0, -5, 5, -10)
  • Large Values: Test with values near 10^15
  • Trace Execution: Manually trace through nested max() calls
  • Compare with 3 Numbers: See how complexity increases
  • Extend to 5: Try adding a 5th number to see which method scales best

📈 Progression: Why This Question Matters

Evolution of the Problem:

  • Question #24 (3 numbers): Manual if-else was feasible
  • Question #25 (4 numbers): Manual approach becomes unwieldy
  • Beyond 4 numbers: Must use scalable approaches (loops, library functions)

Key Programming Insight:

This progression teaches an essential lesson: as problems scale, we must move from manual, explicit logic to algorithmic, pattern-based solutions. This is the foundation of efficient programming!