Question & Answer: Given a set of data, output the middle item (if even number of items, output the two middle items). If the input…..

Given a set of data, output the middle item (if even number of items, output the two middle items). If the input is 5 7 9 11 13 -1 (a negative indicates end), the output is 9. If the input is 5 7 9 11 -1, the output is 7 9.

Given a set of data, output the middle item (if even number of items, output the two middle items). If the input is 57911 13-1 (a negative indicates end), the output is 9. If the input is 579 11 the output is 7 9 Hint: First read the data into a vector. Then, based on the vectors size, find the middle item(s).

Expert Answer

 Your code is as follows: –

#include<iostream>
#include<vector>
using namespace std;

int main() {
vector<int> array;
cout<<“Enter the numbers, to stop enter -1″<<endl;
int x = 0;

while(x != -1) {
cin>>x;
if(x != -1) {
array.push_back(x);
}

}
cout<<“nElements entered :”;
for(int i = 0;i < array.size();i++) {
cout<<array[i]<<” “;
}

int size = array.size();
if(size%2 == 0) {
cout<<“nnMiddle items are: “<<array[(size/2)-1]<<” and “<<array[((size/2))];
} else {
cout<<“nnMiddle item is: “<<array[((size/2))];
}

}

Sample run: –

1.

Enter the numbers, to stop enter -1
1
2
3
4
5
6
7
8
-1

Elements entered :1 2 3 4 5 6 7 8

Middle items are: 4 and 5
——————————–
Process exited after 6.741 seconds with return value 0
Press any key to continue . . .

2.

Enter the numbers, to stop enter -1
1
2
3
4
5
6
7
-1

Elements entered :1 2 3 4 5 6 7

Middle item is: 4
——————————–
Process exited after 6.242 seconds with return value 0
Press any key to continue . . .

Still stressed from student homework?
Get quality assistance from academic writers!