Search code examples
c++arraysfunctionmedian

C++ Issue with median function using arrays


I am having trouble getting this function to work. I am trying to write a median function that takes a user entered array and size, validates that it is correct and then sorts it and displays the median and sorted array. I have tried several different things and no matter what I try I am unable to get this program to work. Any help would be appreciated. Thank you very much.

#include <iostream>
#include <iomanip>


using namespace std;

double median(int n[], int size);

int main(int argc, char** argv) {
    cout << "Calculate The Median of an Array" << endl;
    cout << "---------------------------------" << endl;
    int size, n;
    cout << "Array Size (Maximum is Ten)? ";
    cin >> size;
    if (size > 10 || size < 0) {
        cout << "Invalid size. Please Re-enter." << endl;
    };
    cout << "Array Contents? ";
    cin >> n;
    if ([n] != size) {
        cout << "Invalid Array. Please Re-enter. " << endl;
    };
    median(n, size);
    return 0;
};

double median(int n[], int size) {
     // Allocate an array of the same size and sort it.

    double* dpSorted = new double[size];
    for (int i = 0; i < size; ++i) {
        dpSorted[i] = n[i];
    };

    for (int i = size - 1; i > 0; --i) {
        for (int j = 0; j < i; ++j) {
            if (dpSorted[j] > dpSorted[j+1]) {
                double dTemp = dpSorted[j];
                dpSorted[j] = dpSorted[j+1];
                dpSorted[j+1] = dTemp;
            };
        };
    };

    // Middle or average of middle values in the sorted array.
    int median = 0;
    if ((size % 2) == 0) {
        median = (dpSorted[size/2] + dpSorted[(size/2) - 1])/2.0;
    } 
    else {
       median = dpSorted[size/2];
    };

    cout << "Median of the array " << dpSorted << "is " << median << endl;
};

I am getting the following errors and I cant figure out how to fix them.

34  16  C:\Users\ryanw\Desktop\C++\Labs\Lab 6\main.cpp  [Error] invalid 
conversion from 'int' to 'int*' [-fpermissive]

and

18  8   C:\Users\ryanw\Desktop\C++\Labs\Lab 6\main.cpp  [Note] initializing 
argument 1 of 'double median(int*, int)'

Solution

  • I'm inlining the explanations as comments in the code. Here is the array version. I'm keeping it as close to OP's source as possible.

    #include <iostream>
    #include <iomanip>
    
    
    using namespace std;
    
    double median(int n[], int size);
    
    int main() { // the parameters asre not being used. You can safely leave them out.
        cout << "Calculate The Median of an Array" << endl;
        cout << "---------------------------------" << endl;
        unsigned int size; // unsigned disallows negative numbers. Lest testing required
        int n[10]; // n is an array of 10 elements
        cout << "Array Size (Maximum is Ten)? ";
        cin >> size;
        while (size > 10) { // repeat until user provides a valid size
            cout << "Invalid size. Please Re-enter." << endl;
            cin >> size;
        };
        // the above loop will be an infinite loop if the user types in a value
        // that cannot be converted into an integer.
    
        cout << "Array Contents? ";
        for (unsigned int index = 0; index < size; index++)
        {
            cin >> n[index];
        }
    
        // don't need to test the size. This is ensured by the for loop. Mostly
        // for now we are ignoring the simple problem: "what if the user inputs
        // a value that is not an integer?
        median(n, size);
        return 0;
    }// don't need ; after function.
    
    double median(int n[], int size) {
         // Don't need an array of doubles. Ignoring it.
    
        // assuming the logic here is correct. If it isn't, that's a different
        // topic and another question.
        for (int i = size - 1; i > 0; --i) {
            for (int j = 0; j < i; ++j) {
                if (n[j] > n[j+1]) {
                    int dTemp = n[j];
                    n[j] = n[j+1];
                    n[j+1] = dTemp;
                };
            };
        };
    
        // Middle or average of middle values in the sorted array.
        double result = 0; //reusing an identifier is a dangerous business. Avoid it.
        if ((size % 2) == 0) {
            result = (n[size/2] + n[(size/2) - 1])/2.0;
        }
        else {
            result = n[size/2];
        };
    
        cout << "Median of the array is " << result << endl;
    
        // it's harder to print out an array than I think it should be.
        // Leaving it out for now
    
        // Other than main, a function with a return type must ALWAYS return.
        return result;
    }
    

    And with std::vector and other library wizardry:

    #include <iostream>
    #include <iomanip>
    #include <vector>
    #include <algorithm>
    
    
    // using namespace std; generally should avoid this
    
    // moving median up here so forward declaration isn't needed
    double median(std::vector<int> &n) { //don't need size. Vector knows how big it is
        std::sort(n.begin(), n.end()); // use built-in sort function
    
        double result = 0; 
        auto size = n.size();
        if ((size % 2) == 0) {
            result = (n[size/2] + n[(size/2) - 1])/2.0;
        }
        else {
            result = n[size/2];
        };
    
        // since this function calculates and returns the result, it shouldn't 
        // also print. A function should only do one thing. It make them easier 
        // to debug and more re-usable
        return result;
    }
    
    
    int main() {
        // can chain couts into one
        // endl is more than just a line feed and very expensive. Only use it
        // when you need the message to get out immediately
        std::cout << "Calculate The Median of an Array\n" <<
                     "---------------------------------\n" <<
                     "Array Size (Maximum is Ten)? " << std::endl;
        unsigned int size;
        std::cin >> size;
        while (size > 10) {
            // here we use endle because we want he user to see the message right away
            std::cout << "Invalid size. Please Re-enter:" << std::endl;
            std::cin >> size;
        };
    
        std::vector<int> n(size);
    
        std::cout << "Array Contents? " << std::endl;
        for (int & val: n) // for all elements in n
        {
            std::cin >> val;
        }
    
        std::cout << "Median of the array is " << median(n) << std::endl;
    
        return 0;
    }