Find column with maximum sum in a Matrix using C++.


Suppose we have a matrix of size M x N. We have to find the column, that has a maximum sum. In this program we will not follow some tricky approach, we will traverse the array column-wise, then get the sum of each column, if the sum is the max, then print the sum and the column index.

Example

#include<iostream>
#define M 5
#define N 5
using namespace std;
int colSum(int colIndex, int mat[M][N]){
   int sum = 0;
   for(int i = 0; i<M; i++){
      sum += mat[i][colIndex];
   }
   return sum;
}
void maxColumnSum(int mat[M][N]) {
   int index = -1;
   int maxSum = INT_MIN;
   for (int i = 0; i < N; i++) {
      int sum = colSum(i, mat);
      if (sum > maxSum) {
         maxSum = sum;
         index = i;
      }
   }
   cout << "Index: " << index << ", Column Sum: " << maxSum;
}
int main() {
   int mat[M][N] = {
      { 1, 2, 3, 4, 5 },
      { 5, 3, 1, 4, 2 },
      { 5, 6, 7, 8, 9 },
      { 0, 6, 3, 4, 12 },
      { 9, 7, 12, 4, 3 },
   };
   maxColumnSum(mat);
}

Output

Index: 4, Column Sum: 31

Updated on: 29-Oct-2019

377 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements