Program to find the maximum element in a Matrix in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a matrix of size nXm. Our task is to create a program to find the maximum element in a Matrix in C++.

Problem Description − Here, we need to simply find the largest element of matrix.

Let’s take an example to understand the problem,

Input

mat[3][3] = {{4, 1, 6},
{5, 2, 9},
{7, 3, 0}}

Output

9

Solution Approach

The solution to the problem is by simply traversing the matrix. This is done by using two nested loops, and checking whether each element of the matrix is greater than maxVal. And return the maxVal at the end.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
#define n 3
#define m 3
int CalcMaxVal(int mat[n][m]) {
   int maxVal = mat[0][0];
   for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++)
         if (mat[i][j] > maxVal)
            maxVal = mat[i][j];
   return maxVal;
}
int main(){
   int mat[n][m] = {{4, 1, 6},{5, 2, 9},{7, 3, 0}};
   cout<<"The maximum element in a Matrix is "<<CalcMaxVal(mat);
   return 0;
}

Output

The maximum element in a Matrix is 9
raja
Published on 08-Jun-2020 10:42:05
Advertisements