Mean and Median of a matrix in C++

C++Server Side ProgrammingProgramming

Problem statement

Given a sorted matrix of size n*n. Calculate the mean and median of the matrix

Consider below matrix −

Matrix[3][3] = {
   {1, 2, 3},
   {4, 5, 6},
   {7, 8, 9}
}
In above matrix Mean = 3 and Median = 5

Algorithms

1. Mean of matrix is (sum of all elements of matrix) / (total elements of matrix).
2. Median of a sorted matrix is calculated as:
   a. When n is odd median is matrix[n/2][n/2]
   b. When n is even, median is average of middle two elements. Middle two elements
      can be found at indexes matrix[(n-2)/2][n-1] and matrix[n/2][0]

Example

#include <bits/stdc++.h>
using namespace std;
const int N = 3;
double findMean(int a[][N]){
   int sum = 0;
   for (int i = 0; i < N; ++i) {
      for (int j = 0; j < N; ++j) {
         sum += a[i][j];
      }
   }
   return (double)sum/(N*N);
}
double findMedian(int a[][N]){
   if (N % 2 != 0) {
      return a[N/2][N/2];
   }
   return (a[(N-2)/2][N-1] + a[N/2][0])/2.0;
}
int main(){
   int a[N][N]= {
      {1, 2, 3},
      {4, 5, 6},
      {7, 8, 9}
   };
   cout << "Mean = " << findMean(a) << endl << "Median = "<< findMedian(a) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Mean = 5
Median = 5
raja
Published on 10-Feb-2020 10:04:16
Advertisements