In statistics, when a set of values is sorted in ascending or descending order,
ID: 3915590 • Letter: I
Question
In statistics, when a set of values is sorted in ascending or descending order, its median is the middle value. If the set contains an even number of values, the median is the mean, or average, of the two middle values. Write a function that accepts as arguments the following: ? an array of integers, ? an integer that indicates the number of elements in the array. The function should determine the median of the array. This value should be returned as a double. (Assume the values in the array are already sorted.) Demonstrate your pointer prowess by using pointer notation instead of array notation in this function.
Explanation / Answer
ScreenShot
-----------------------------------------------------------------------------------------------
Program
//Header file for I/O
#include<iostream>
using namespace std;
//Function median prototype
double median(double *arr, int size);
//Test For function
int main()
{
//Variable for array size
int size;
//Pointer array
double *arr;
//Prompt user to enter size of the array
cout << "Please enter the size of the array: ";
cin >> size;
//Assure size of the array always greater than 3
while (size < 3) {
cout << "Size always greater than 2!!" << endl;
cout << "Please enter the size of the array: ";
cin >> size;
}
//Initialize array size
arr = new double[size];
//Prompt to enter array values always sorted
for (int i = 0; i < size; i++) {
cout << "Enter elements into the array: ";
cin >> *(arr + i);
}
//Display entered array elements
cout << "Array values: " << endl;
for (int i = 0; i < size; i++) {
cout << *(arr + i) << endl;
}
//Display median
cout << "Meadian= " << median(arr, size) << endl;
//Freed the space
delete[]arr;
return 0;
}
//Find median of the array
double median(double *arr, int size) {
//If odd size array median=middle element of the array
if (size % 2 == 1) {
int ind = size / 2;
return *(arr + ind);
}
//if size even median is the two middle elements average
else {
int ind1 = size / 2;
int ind2 = ind1 - 1;
return (((*arr + ind1) + *(arr + ind2)) / 2);
}
}
----------------------------------------------------------------------------------------------
Output
Please enter the size of the array: 5
Enter elements into the array: 2
Enter elements into the array: 4
Enter elements into the array: 6
Enter elements into the array: 8
Enter elements into the array: 10
Array values:
2
4
6
8
10
Meadian= 6
Press any key to continue . . .
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.