C++ Programming Challenge #9.9: Median Function In statistics, when a set of val
ID: 3686422 • Letter: C
Question
C++
Programming Challenge #9.9: Median Function
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.
Thanks!
Explanation / Answer
Solution.cpp
#include<iostream>//header file for input or output functions
using namespace std;//it tells the compiler tolink std namespace
double get_Median(int*,int);//function declaration
double get_Median(int* numbers,int size)
{//function definition
//sort number
int leastValue,minIndex;
for(int i=0;i<size-1;i++)
{
leastValue=numbers[i];
minIndex=i;
for(int index=i+1;index<size;index++)
{
if(numbers[i]>numbers[index])
{
leastValue=numbers[index];
minIndex=index;
}
}
numbers[minIndex]=numbers[i];
numbers[i]=leastValue;
}
//get_median
double median;
if(size%2==0)
median=(numbers[size/2]+numbers[size/2-1])/2.0;
else
median=numbers[(size-1)/2];
return median;
}
int main()
{//main function which return integer
int size;
cout<<"Enter the number of elements either in ascending order or descding order: ";
cin>>size;
int* elements=new int[size];
for(int i=0;i<size;i++)
{
cout<<" Enter the "<<i+1<<" number: ";
cin>>elements[i];
}
double median=get_Median(elements,size);//function calling
cout<<median<<endl;
return 0;
}
output
sh-4.3$ main
Enter the number of elements either in ascending order or descding order: 6
Enter the 1 number: 10 Enter the 2 number: 20 Enter the 3 number: 30 Enter the 4 number: 40 Enter the 5 number: 50 Enter the 6 number: 60
35
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.