Finding the sum of individual columns in matrix

Dec 4, 2015 at 6:53pm
I need to write a program that prints the sum of each individual column in a matrix. My code currently prints out compounded sum of the columns.

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
36
 #include <iostream>
using namespace std;

const int SIZE = 4;
double sumColumn(const double m[][SIZE], int rowSize, int columnIndex){

  double sum =0;
  for(int x = 0; x < 4; x++){
   for(int y = 0; y <=3; y++){

    sum+= m[x][y]; 


   }
  }
 return sum;
}

int main ()
{   
    double m[3][4] = {};
    cout << "Enter a 3-by-4 matrix row by row" << endl;
    for(int x = 0; x<3; x++){
        for(int y = 0; y<4; y++){
            cin >> m[x][y];
        }
      }

      int rowSize = 4;

      for(int x= 0; x<4; x++){
       cout << "Sum of the elements at column " << x << " " << sumColumn(m, rowSize, x) << endl;   
      }


}

Input:

1.5 2 3 4

5.5 6 7 8

9.5 1 3 1

Output:

Sum of the elements at column 0 16.5

Sum of the elements at column 1 25.5

Sum of the elements at column 2 38.5

Sum of the elements at column 3 51.5

It should be 16.5, 9, 13, 13. How can I change my sumColumn function so that it breaks out when it hits a new column or how can I get it so that the sum resets? I tried adding a break statement and reseting sum to 0, but neither of those things worked. Any ideas? Thanks.
Dec 4, 2015 at 8:11pm
Do you think maybe you should use that parameter you feed to sumColumn named columnIndex for something?

I'm not sure how you come up with different values for the different columns, since you add the sum the same values every time. Although, perhaps that's a result of the undefined behavior for accessing outside the bounds of your array.
Dec 4, 2015 at 8:47pm
Oh sorry the code I posted was not my updated code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
double sumColumn(const double m[][SIZE], int rowSize, int columnIndex){
  double sum =0;
  
  for(int x = 0; x < 4; x++){
      
   for(int y = 0; y <=columnIndex; y++){
    
    sum+= m[x][y]; 
    
      
    
   }
  }
 
 return sum;
}


With this I get the output I described in my original post. I just wasn't sure how to fix this.
Dec 4, 2015 at 10:15pm
To loop over a single column or single row, you need a single loop.

1
2
3
4
5
6
7
8
9
double sumColumn(const double m[][SIZE], int numRows, int column)
{
    double sum = 0.0;

    for (int row=0; row < numRows; ++row)
        sum += m[row][column] ;

    return sum;
}



Dec 4, 2015 at 11:35pm
Oh okay that makes sense. Thanks!
Topic archived. No new replies allowed.