Hassaan Iqbal
Hassaan Iqbal

Reputation: 21

C++ Print Row Number along with Maximum Sum of Rows 2D Arrays

I am trying to calculate the sum of rows in 2d array and compare the maximum sum of row with other rows. I successfully calculated the sum of each row and also compared the row's maximum with other rows but problem I am currently facing is I don't know how to print the row number that has maximum sum. Here is a piece of code that I am working on:

void calculateMaxRowSum(int array[10][10])
{
     int maxsum = 0;
     for(int i=0;i<10;i++) 
     {  
          int sum = 0;  
          for(int j=0;j<10;j++)
          {
               sum = sum + array[i][j];
          }
               if(sum > maxsum)
                    maxsum = sum;
     }
     cout<<"Row No. "<<(Problem is here)<<" has maximum sum: "<<maxsum<<endl;
}

Please help me out. Thanks!!!

Upvotes: 0

Views: 1640

Answers (1)

Simon Kraemer
Simon Kraemer

Reputation: 5680

You must remember your rownumber

#include <string>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <cstring>

using namespace std;

void calculateMaxRowSum(int array[10][10])
{
    int maxrow = -1;
    int maxsum = 0;
    for (int i = 0; i<10; i++)
    {
        int sum = 0;
        for (int j = 0; j<10; j++)
        {
            sum = sum + array[i][j];
        }
        if (sum > maxsum)
        {
            maxrow = i;
            maxsum = sum;
        }
    }
    cout << "Row No. " << maxrow << " has maximum sum: " << maxsum << endl;
}
int main() {
    int arr[10][10] = { 
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 0
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 1
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 2
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 3
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 4
        { 9,1,1,1,1,1,1,1,1,1}, //Row No. 5 //MAX
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 6
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 7
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 8
        { 1,1,1,1,1,1,1,1,1,1}  //Row No. 9
    };

    calculateMaxRowSum(arr);
}

Upvotes: 1

Related Questions