Saturday, June 20, 2020

Greatest sum

Seenu have a fruit shop. He is arranged the some set of fruits are column and row wise. Seenu needs to find which row and column has maximum number of fruits. Help him to find out.

INPUT & OUTPUT FORMAT:

Input consists of 2 integers and 1 2D-array. Integers correspond to the size of rows and columns.

SAMPLE INPUT & OUTPUT:

3

3

1 6 8

2 5 1

3 8 2

Sum of rows is 15 8 13

Row 1 has maximum sum

Sum of columns is 6 19 11

Column 2 has maximum sum

SOLUTION:

#include<iostream>

using namespace std;

int main(){

int r, c, row, col, sum = 0, row_ind = 0, col_ind = 0;

cin >> r >> c;

int row_arr[r];

int i, j;

int mat[r][c];

for(i = 0; i < r; i++){

for(j = 0; j < c; j++)

cin >> mat[i][j];

}

int z = 0;

cout << "Sum of rows is ";

for(row=0; row<r; row++){

sum = 0;

for(col=0; col<c; col++){

sum += mat[row][col];

}

cout << sum <<" ";

row_arr[z++] = sum;

}

cout<<"\n";  

int temp_row = row_arr[0];

for(i=1;i<r;i++){

if(temp_row < row_arr[i]){

temp_row = row_arr[i];

row_ind = i;

}

}

cout<<"Row "<<row_ind + 1<<" has maximum sum"<<endl;

sum = 0;

int y = 0;

int col_arr[c];

cout<<"Sum of columns is ";

for (i = 0; i < c; ++i){

sum = 0;

for (j = 0; j < r; ++j){

sum = sum + mat[j][i];

}

cout<<sum<<" ";

col_arr[y++] = sum;

}

cout<<"\n";

int temp_col = col_arr[0];

for(i=1;i<c;i++){

if(temp_col < col_arr[i]){

temp_col = col_arr[i];

col_ind = i;

}

}

cout<<"Column "<<col_ind + 1<<" has maximum sum"<<endl;

return 0;

}

No comments:

Post a Comment

horizontal ads