The assignment is to create a program that displays the median of an array using pointers. Assume the array is already in ascending or descending order.
I'm getting errors currently on the bottom two "return median;" statements. Any ideas/corrections would be appreciated.
#include <iostream>
usingnamespace std;
char again;
int getMedian(int*, int);
constint constant = 100;
int main()
{
do
{
int number;
int *array;
int median = 0;
cout << "Enter the number of values in ascending or descending order: ";
cin >> number;
array = newint[number];
for (int count=0; count < number; count++)
{
cout<<"Enter number #"<<(count+1)<<": ";
cin >> array[count];
}
median = getMedian(array, number);
cout << "The median is " << median ;
cout << "\nDo you want to run this program again? Y/N: ";
cin >> again;
} while (again == 'y' || again == 'Y');
return 0;
}
void getMedian(double *array, int size)
{
int midIndex = 0;
double median = 0;
if ((size % 2)!= 0)
{
midIndex = ((size - 1) / 2);
median = array[midIndex];
return median;
}
else
{
midIndex = size / 2;
median = ((array[midIndex] + array[midIndex +1]) /2);
return median;
}
}
1. The return type of getMedian is void. Yet you are trying to return median.
2. The type of the first formal parameter of your function is double* while the type of your first actual parameter is int*. You can't do this.
#include <iostream>
usingnamespace std;
char again;
int getMedian(double*, int);
constint constant = 100;
int main()
{
do
{
int number;
double *array;
int median = 0;
cout << "Enter the number of values in ascending or descending order: ";
cin >> number;
array = newint[number];
for (int count=0; count < number; count++)
{
cout<<"Enter number #"<<(count+1)<<": ";
cin >> array[count];
}
median = getMedian(array, number);
cout << "The median is " << median ;
cout << "\nDo you want to run this program again? Y/N: ";
cin >> again;
} while (again == 'y' || again == 'Y');
return 0;
}
getMedian(double *array, int size)
{
int midIndex = 0;
double median = 0;
int size;
if ((size % 2)!= 0)
{
midIndex = ((size - 1) / 2);
median = array[midIndex];
return median;
}
else
{
midIndex = size / 2;
median = ((array[midIndex] + array[midIndex +1]) /2);
return median;
}
}
If you don't delete the array (L20) you will have a memory leak.
If you cycle through the array and get the highest and lowest values, isn't the median value just ( highest - lowest) /2? ... or can it also be the element closest to this previous theoretical value? With an int type array you loose the remainder when dividing by 2.