I\'m trying to write a function in C++ using codeblocks. The function is suppose
ID: 3849921 • Letter: I
Question
I'm trying to write a function in C++ using codeblocks. The function is supposed to calculate the median value of an array here is what I have so far in medianFunc:
Can somebody show me code to run medianFunc so it prints out median value of dynamic array on the console
#include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <iomanip>
using std::fixed;
using std::setprecision;
using std::cout;
using std::cin;
using std::endl;
// Function declarations and definitions
/* Function of given size and populated with random
values between 0 - 100
*/
void myFunc(int* array, const unsigned int size){
srand(time(nullptr));
cout << "[";
for(int i = 0; i < size; ++i)
{
array[i] = rand() % 100;
cout << " " << array[i];
}
cout << " ]" << endl;
}
/* Function to calculate the average of the array
should take as arguments the array and its size
*/
void avgFunc(int* array, const unsigned int size){
double sum = 0;
double avg = 0;
int* myArray = array;
for(int i = 0; i < size; ++i){
sum += myArray[i];
}
avg = sum / size;
cout << fixed << setprecision(2) << "The average is: " << avg << endl;
}
// Function to calculate median should take as arguments the array and it size
void medianFunc(int* array, const unsigned int size){
int* myArray = array;
double median = 0;
int middle = 0;
double middle1 = 0;
double middle2 = 0;
if(middle == sizeof(myArray) / 2){
median = (myArray[1] + myArray[2]) / 2;
cout << "The median is: " << median << endl;
}
else{
median = myArray[2];
cout << "The median is: " << median << endl;
}
}
int main()
{
int* myArray;
unsigned int mySize;
cout << "Enter array size: ";
cin >> mySize;
int* theSize = new int[mySize];
myFunc(myArray, mySize);
avgFunc(myArray, mySize);
medianFunc(myArray, mySize);
delete[] myArray;
return 0;
}
Explanation / Answer
void medianFunc(int* array, const unsigned int size){
int** myArray = new int*[size]; //create an array of pointer
for (int i = 0; i < size; i++) //initialize array of pointers with pointers pointing all elements of array
myArray[i] = array + i;
for (int i = 0; i < size - 1; i++) //sort myArray
for (int j = 0; j < size - i - 1; j++)
if (*myArray[j] > *myArray[j+1]) {
int *tmp = myArray[j];
myArray[j] = myArray[j+1];
myArray[j+1] = tmp;
}
double median;
if (size%2==0)
median = (double)(*myArray[size/2] + *myArray[size/2 - 1])/2;
else
median = *myArray[size/2];
cout << "Median is: " << median << endl;
}
As you can see we have used pointers to pointers and sorted that array, because if we had sorted the array in the parameter, the changes would have been visible else where, and that is not desired. So by using pointer to pointer array, we can sort this array bt the changes would be local since it does not touch the original array ever.
I hope am clear to you. Let me know if you need any help from my side.