Answer to Question #22038 in C++ for rodea embradura

Question #22038
the median of a set of integers is the value which divides the set exactly in half. Given a one-dimensional array whose elements are sorted from lowest to highest, the median can be determined by applying the following rules:

a) if the number of elements in the array is odd, the element in the middle of the array is the median.

b) if the number of elements in the array is even, the median is computed as the average of the two middle elements.

Write a program that will accept the number of elements in the array and the data elements as inputs. Display the array's elements along with the median.
1
Expert's answer
2013-01-17T09:40:50-0500
#include <conio.h>
#include <iostream>

using namespace std;

void main()
{
int* array;
int arrayLength;
float median;

/* Input the number of elements in array */
cout << "Enter array size: ";
cin >> arrayLength;

/* Allocate memory for the array */
array = new int[arrayLength];
cout << "Enter " << arrayLength << " array elements sorted from lowest to highest." << endl;

/* Input array elements */
for (int y = 0; y < arrayLength; y++)
cin >> array[y];
cout << endl;

/* Find the median */
if (arrayLength % 2 == 0)
median = (array[arrayLength / 2] + array[arrayLength / 2 - 1]) / 2;
else
median = array[arrayLength / 2];

/* Display array elements */
cout << "Array elements:" << endl;
for (int u = 0; u < arrayLength; u++)
cout << array[u] << ' ';
cout << endl;

/* Output the found median */
cout << "The median is: " << median << endl;

delete[] array;
getch();
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS