How to claculate the sum or product of each row and column separately in a 2-d array.
You'll need arrays with the same number of elements (or you could use a vector) to place the results in.
C++ish code:
template<class T>
vector<T> SumRows(T * array, unsigned int rows, unsigned int cols)
{
vector<T> sums;
for ( unsigned int i = 0; i < rows; i++ )
{
T sum = 0;
for ( unsigned int j = 0; j < cols; j++ )
{
sum += array[i][j];
}
sums.push_back(sum);
}
return sums;
}
I templated it for fun, but it relies on a type that has a the = and += operators and can be assigned an int constant. Call that function with a pointer to the first element (or just use the array), the appropriate type and counts. For example:
int myArray[3][3];
vector<int> sums = SumRows<int>(myArray, 3, 3);
Columns sums works similarly, just reverse the rows and cols position in the for loops.
One possibility would to use std::accumulate, which is designed for exactly this kind of situation.
I hesitate to mention it, but the C++ standard library offers another possibility that was designed even more specifically for this kind of use. std::valarray overloads many of the standard mathematical operators to make this sort of thing almost trivial. The problem is that it's poorly documented and so rarely used, that even though it can do the job, almost any use of valarray at least borders on obfuscating your code.