# 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.

Expert's answer

#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();

}

#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();

}

## Comments

## Leave a comment