
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements