85.6k views
4 votes
In C++ please

6.19 LAB: Middle item
Given a sorted list of integers, output the middle integer. A negative number indicates the end of the input (the negative number is not a part of the sorted list). Assume the number of integers is always odd.

Ex: If the input is:

2 3 4 8 11 -1
the output is:

Middle item: 4
The maximum number of list values for any test case should not exceed 9. If exceeded, output "Too many numbers".

Hint: First read the data into a vector. Then, based on the number of items, find the middle item.

In C++ please 6.19 LAB: Middle item Given a sorted list of integers, output the middle-example-1
User Yousef
by
7.9k points

1 Answer

4 votes

Answer:

#include <iostream>

#include <vector>

using namespace std;

int main() {

vector<int> data;

int num;

cin >> num;

// Read values into vector

while (num >= 0) {

data.push_back(num);

cin >> num;

}

// Check if too many numbers

if (data.size() > 9) {

cout << "Too many numbers";

}

else {

// Print middle item

int mid = data.size() / 2;

cout << "Middle item: " << data.at(mid);

}

return 0;

}

User David Fritsch
by
7.7k points