Write a program that adds up the largest row sum and the largest column sum from an N rows*M-columns array of numbers. As a preliminary phrase, you should reformat the sequence of numbers as a matrix, whose number of rows and columns are to be specified as arguments.
Answers
Program in C++:
#include<iostream>
using namespace std;
int main()
{
int N, M;
cout<<"Enter number of rows : ";
cin>>N;
cout<<"\nEnter number of columns : ";
cin>>M;
int Matrix[N][M];
cout<<"\nEnter elements row-wise : \n";
for(int i = 0; i < N; i++)
{
for(int j = 0; j < M; j++)
{
cin>>Matrix[i][j];
}
}
cout<<"\nMatrix is : "<<endl;
for(int i = 0; i < N; i++)
{
for(int j = 0; j < M; j++)
{
cout<<Matrix[i][j]<<"\t";
}
cout<<endl;
}
int Row = 0;
for(int i = 0; i < N; i++)
{
int sum = 0;
for(int j = 0; j < M; j++)
{
sum = sum + Matrix[i][j];
}
if(Row < sum)
{
Row = sum;
}
}
cout<<"\nLargest row sum : "<<Row<<endl;
int Column = 0;
for(int i = 0; i < M; i++)
{
int sum = 0;
for(int j = 0; j < N; j++)
{
sum = sum + Matrix[j][i];
}
if(Column < sum)
{
Column = sum;
}
}
cout<<"\nLargest column sum : "<<Column;
return 0;
}
Output:
Enter number of rows : 3
Enter number of columns : 3
Enter elements row-wise :
1
2
3
4
5
6
7
8
9
Matrix is :
1 2 3
4 5 6
7 8 9
Largest row sum : 24
Largest column sum : 18
Answer:
Program in C++:
//return sum of rowsum Max and columnSum max
int findSum(int n,int m,int arr[]){
int rsum = 0, csum = 0;
int i = 0;
int c = 0;
int j = 0, curr = 0;
while (i < n * m) {
curr += arr[i];
if (j == m - 1) {
rsum = max(rsum, curr);
curr = 0;
j = -1;
c++;
}
j++;
i++;
}
for (i = 0; i < m; i++) {
j = i;
int cr = 0;
while (j < n * m) {
cr += arr[j];
j += m;
}
csum = max(csum, cr);
}
return rsum+csum;
}
Explanation:
We have a 1-D array(arr) and no. of rows(n) and column(m) of 2D array that is in the form of this 1D array .
We have to find sum of maximum of sum of all rows and maximum of sum of all column.