Please help I am writing a program that calculates the mean and median of a sequence of integers. My program works fine as long as the array is odd. Can someone please help me with a statement to calculate the median when the array is even. I have included my code for the program.

#include <iostream>

   float mean   (const int* A, size_t size); //calculates mean of data in A
   float median (int* A, size_t size); // calculates median of data in A
   void swap    (int& x, int& y); //  interchanges values of x and y
   void sort    (int*A, size_t size); // sorts the data in A
   void bubblesort (int, int);

int main()
{
 int n;
 size_t size;
 int A [100]; size = 0;
 std::cout << "Enter data to calculate the mean and median: ";
 while((std::cin >> n) && (size < 100))
   {
     A[size] = n;
     ++size;
   }

 for (size_t i = 0; i < size; i++)
 std::cout << A[i] << ' ';
 std::cout << '\n';

std::cout << "The mean of the data entered is:   "  << mean(A,size) << '\n';
 std::cout << "The median of the data entered is: "  << median(A,size)<< '\n';

 for (size_t i = 0; i < size; i++)
   std::cout << A[i] << ' ';
 std::cout << '\n';
 return 0;
}

float mean(const int* A, size_t size)
 {
  float total = 0;
   for (size_t i = 0; i < size; i++)
     total += A[i];
   return total / size;
 }

 float median(int* A, size_t size)
 {
   sort(A,size);
   return A[size/2];
 }

 void swap(int& x, int& y)
 {
   int hold = x;
   x = y;
   y = hold;
 }

 void sort(int* A, size_t size)
   // bubble sort
{
   for (size_t pass = 0; pass < size - 1; pass ++)
      for (size_t j = 0; j < size - 1; j++)
         if (A[j] > A[j + 1])
           swap(A[j], A[j+1]);
 }

Dani AI

Generated

A few clarifications and a robust approach.

For an even-length sequence the median is the average of the two middle values (zero-based indices n/2 - 1 and n/2). started that idea and correctly pointed out you must compute the mean of those two values; 's posts contain indexing/parenthesis mistakes. Two practical gotchas in the original program: (1) integer division truncates, so you must force a floating-point average, and (2) your median sorts the array in-place, which will change the sequence printed later — copy the data first if you need the original order.

A safer C++ routine that preserves the original input and avoids a full sort (useful for large arrays) uses std::nth_element and a safe averaging formula to avoid overflow:

#include <vector>
#include <algorithm>
#include <stdexcept>

double median_copy(const int* A, size_t n) {
    if (n == 0) throw std::invalid_argument("empty");
    std::vector<int> v(A, A + n);          // preserve original
    size_t mid = n / 2;
    if (n % 2 == 1) {
        std::nth_element(v.begin(), v.begin()+mid, v.end());
        return static_cast<double>(v[mid]);
    } else {
        std::nth_element(v.begin(), v.begin()+mid, v.end());
        int hi = v[mid];
        std::nth_element(v.begin(), v.begin()+mid-1, v.end());
        int lo = v[mid-1];
        return lo + (hi - lo) / 2.0;      // avoids int overflow and truncation
    }
}

Quick tips: use double (or long double) for the median/mean result to avoid truncation; if you only need the median once on a large input prefer std::nth_element over std::sort; check n==0 and handle it; when summing many ints use a wide accumulator (double or 64-bit) to reduce overflow risk. For Python, the standard library already handles this: import statistics; statistics.median(data).

Recommended Answers

All 9 Replies

>Can someone please help me with a statement to calculate the median when the array is even.
Take the median of the two middle items: a and a.

>>Can someone please help me with a statement to calculate the median when the array is even.
>Take the median of the two middle items: a and a.
Wouldn't that be the mean of a and a[size / 2 - 1]?

>>Can someone please help me with a statement to calculate the median when the array is even.
>Take the median of the two middle items: a and a.
Wouldn't that be the mean of a and a[size / 2 - 1]?

Feh, you're no fun. ;)

((n/2)+(n+1)/2)/2

n is the nmber of elements in the array

i e
if yr array was x[n];
median = ((x[n]/2)+(x[n]+1)/2)/2;

((n/2)+(n+1)/2)/2

n is the nmber of elements in the array

i e
if yr array was x[n];
median = ((x[n]/2)+(x[n]+1)/2)/2;

sorry again it will b ((x[n]/2)+(x[n+1])/2)/2

sorry again it will b ((x[n]/2)+(x[n+1])/2)/2

Really?

#include <iostream>
 
 float median(int* x, int n)
 {
    return ((x[n]/2)+(x[n+1])/2)/2;
 }
 
 int main()
 {
    int i, A[] = {1,2,3,4,5,6,7,8,9,10}, size = sizeof A / sizeof *A;
    float result = median(A, size);
    for ( i = 0; i < size; i++ )
    {
 	  std::cout << A[i] << ' ';
    }
    std::cout << "\nThe median of the data entered is: " << result << '\n';
    return 0;
 }
 
 /* my output
 1 2 3 4 5 6 7 8 9 10
 The median of the data entered is: 1.38446e+06
 */

float median(int* x, int n)
{
return ((x[n/2])+(x[(n/2)+1]))/2;
}

tell me when it works

Uh... look up.

Oh nevermind.

float median(int* x, int n)
 {
    return ( x [ n / 2 ] + x [ n / 2 - 1] ) / 2.0F;
 }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.