Need help with 2D Arrays!

Suppose you have a 2D Array that looks something like this,

1 2 3 4 5
2 3 4 5 6
3 4 5 6 7

How would you find the total of each row and display what the highest total score is.

1
2
3
4
5
6
7
8
9
for(int i=0; i<3; i++){
for(int j=0; j<5; j++){
sum+=integers[i][j]
largest=0;
if(sum > largest){
largest = sum;
}
}
}


This is the segment of code I came up with. Any help is appreciated.
Last edited on
You could store all totals in an one-dimensional array and then find the highest value from this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <limits>

int main()
{
    int arr[3][5] = { {1,2,3,4,5},
                      {2,3,4,5,6},
                      {3,4,5,6,7}
                  };
    int totals[3] = {0};
    
    for( int i = 0; i < 3; ++i)
        for( int k = 0; k < 5; ++k)
            totals[i] += arr[i][k];
    
    int highest = std::numeric_limits<int>::min();
    for( int i = 0; i < 3; ++i)
        if ( totals[i] > highest)
            highest = totals[i];
            
    std::cout << highest;
    
}
Last edited on
Thank you so much!
closed account (E0p9LyTq)
An alternative without the need for a 1D array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <limits>

int main()
{
   int arr[3][5] = { {1, 2, 3, 4, 5},
                     {3, 4, 5, 6, 7},
                     {2, 3, 4, 5, 6} };


   int highest = std::numeric_limits<int>::min();
   int index   = 0;

   for (int i = 0; i < 3; ++i)
   {
      int totals = 0;

      for (int j = 0; j < 5; j++)
      {
         totals += arr[i][j];
      }

      if (totals > highest)
      {
         highest = totals;
         index = i;
      }
   }

   std::cout << highest << '\t' << index << '\n';
}
Topic archived. No new replies allowed.