C++ Online Compiler
Example: Find Middle Max and Min in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Find Middle Max and Min #include <iostream> // Required for input/output operations #include <vector> // Required for using std::vector #include <algorithm> // Required for std::sort int main() { std::vector<int> numbers; // Step 1: Declare a vector to store user input int num; std::cout << "Enter integers (enter a non-integer or Ctrl+D/Z to stop):\n"; // Step 2: Read integers from user input until an invalid input is given while (std::cin >> num) { numbers.push_back(num); } // Clear error flags and ignore remaining input in the buffer std::cin.clear(); // std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Might be needed if using std::getline later // Step 3: Check if there are enough numbers to find distinct middle values if (numbers.size() < 2) { if (numbers.empty()) { std::cout << "No numbers entered. Cannot find middle max/min.\n"; } else { std::cout << "Only one number entered: " << numbers[0] << ". Middle max and min are both: " << numbers[0] << "\n"; } return 0; } // Step 4: Sort the vector in ascending order std::sort(numbers.begin(), numbers.end()); // Step 5: Calculate indices for middle minimum and maximum // For a vector of size N, indices are 0 to N-1. // Middle minimum is at index (N/2) - 1 // Middle maximum is at index (N/2) size_t mid_min_index = (numbers.size() / 2) - 1; size_t mid_max_index = (numbers.size() / 2); // Step 6: Retrieve and print the middle maximum and minimum values int middle_min_value = numbers[mid_min_index]; int middle_max_value = numbers[mid_max_index]; std::cout << "\nSorted numbers: "; for (int n : numbers) { std::cout << n << " "; } std::cout << "\n"; std::cout << "Middle Minimum Value: " << middle_min_value << "\n"; std::cout << "Middle Maximum Value: " << middle_max_value << "\n"; return 0; }
Output
Clear
ADVERTISEMENTS