finding sum of 2-d array

closed account (i8bjz8AR)
So i'm just trying to find the sum of rows and columns of this 2-d array. I keep getting the same output and feel like I'm not actually calculating a sum, here is what i have:
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
32
33
34
35
#include <iostream>

using namespace std;

int main()
{
    int row, col, i,j;
   int array [4][7];
    cout << "Find the sum of each row: ";
    cin >> row;
    cout << "Find the sum of each column: ";
    cin >> col;
    cout << endl;
    for(i=1; i <= row; i++)
    {

        for(j=1; j<= col; j++)
        {
             cout << "Row " << i << "Column " << j;
            cin >> array[i][j];
        }
        cout << endl<< "Matrix" << endl;

    }
     for(i; i <= row; i++)
    {

        for(j; j<= col; j++)
        {
             cout << array[i][j]<<"\t";

        }

}
}
Where are you actually adding up the rows and columns? I don't see any addition anywhere.
closed account (i8bjz8AR)
yeah i guess i see all i was doing now was outputting the first row and column of the array, the adding part still confused me a little bit...
Well, you're already going through some of the rows. You can just sum up each row as you iterate through it. The row index will stay constant as you index through. The same sort of idea goes for summing up the columns.
closed account (i8bjz8AR)
okay i'm confused about summing up each row as i iterate through it. so would it be like row += array[]?
kind of...

So, here's your array. It's a different size than yours, but the same logic applies.

| 1 | 2 | 3 | 4 | 5 | 6 |
| 7 | 8 | 9 |10|11|12|
|13|14|15|16|17|18|

When you go to (0, 0), that gives you '1', right? Going to (0, 1) would give you '2'? (0, 2) gives you '3', and so forth. You're iterating through 'row 0' and the row index stays the same as you vary the column index from 0 to numcols - 1. Just do that for each row.
Similarly for the column, but the order is switched and this time the column index stays the same as you vary the row index.

So, as you go through, you could so something like rowSum += array[row][col]
You just have to be sure to initialize rowSum to 0 at the beginning of each row.
Similarly for the column sum.
Topic archived. No new replies allowed.