#include <iostream>
usingnamespace std;
constint SIZE = 4;
double sumColumn(constdouble 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.
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.
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(constdouble 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.