Mean and Median of a matrix in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a 2D array of size n*n. Our task is to create a program that will print the mean and median of the matrix in C++.

Mean is the average of the date set. In a matrix mean is the average of all elements of the matrix.

Mean = (sum of all elements of the matrix)/(number of elements of the matrix)

Median is the middlemost element of the sorted data set. For this, we will have to sort the elements of the matrix.

Median is calculated as,

If n is odd, median = matrix[n/2][n/2]

If n is even, median = ((matrix[(n-2)/2][n-1])+(matrix[n/2][0]))/2


Program to illustrate the working of our solution

 Live Demo

#include <iostream>
using namespace std;
const int N = 4;
int calcMean(int Matrix[][N]) {
   int sum = 0;
   for (int i=0; i<N; i++)
      for (int j=0; j<N; j++)
         sum += Matrix[i][j];
      return (int)sum/(N*N);
   int calcMedian(int Matrix[][N]) {
      if (N % 2 != 0)
         return Matrix[N/2][N/2];
      if (N%2 == 0)
         return (Matrix[(N-2)/2][N-1] + Matrix[N/2][0])/2;
int main() {
   int Matrix[N][N]= {
      {5, 10, 15, 20},
      {25, 30, 35, 40},
      {45, 50, 55, 60},
      {65, 70, 75, 80}};
   cout<<"Mean of the matrix: "<<calcMean(Matrix)<<endl;
   cout<<"Median of the matrix : "<<calcMedian(Matrix)<<endl;
   return 0;


Mean of the matrix: 42
Median of the matrix : 42
Published on 10-Feb-2020 10:04:16