writing an iterative loop to compute sum of matrix

Consider a 2-d Matrix (square) of size N x N a column

a. Write an iterative (loop) code segment (algorithm) to compute the sum of the values in each column (one sum per column).

b. Assuming the work unit of interest is the addition used in the summations, analyze your algorithm in terms of work and the size of the matrix (N)

c Now consider a 3-d Matrix (cube) of size Nx Nx N a column Write an iterative code segment (algorithm) to compute the sum of the values in each column (one sum per column).


d. Assuming the work unit of interest is the addition used in the summations, analyze your algorithm in terms of work and the size of the matrix (N).
Hi,

Could you show us what you did/tried?

P.S. This isn't a homework site :)
int A[n][n], i, j, c[n], row, col;

for(j=0; j < col; j++)
{
c[j]=0;
for (i=0; i < row; i++)
{
c[j] = c[j] + A[i][j];
}
}
//sum of columns
row and col appear to be uninitialized.
you probably need
row=col=n;
or just use n in the loops.

also we can't tell but n has to be a compile time constant (though some compilers will tolerate it as a variable, this is not correct).

so you need something like
//forgetting about N
const int row = 10;
const int col = 10;
int A[row][col];
int c[col] = {0};
...
your code will work here now, but it is nonsense because A has uninitialized data. you may want a loop to put values into it. If you set all the values of A to the same number (1 would be simple) you can see if you got the correct answer (if you put in 1, and use 10/10 for row/col, it would give 10 for each col, right?)

Last edited on
Topic archived. No new replies allowed.