Help with getting sum of diagonals (C lang)

Hi
i try to write a function that gets a matrix,row,col

int r_c_sum(int ar[N][N],int row,int col)

the function calculates the diagonal thats in the row and col
ex:

1 2 3 5
4 5 6 1
7 7 7 3
4 5 6 4
if row=1 col=2


it needs to return the sum of 6+2+3 = 11
please help me because i didn't find out how to do it
thanks
Last edited on
Is the diagonal always going to be upper left to lower right?

wouldn't that just be the incrementing the row and the col, checking for out of bounds indices along the way?
the diagonal goes depending to the row and colume that the user enter
it can be also : row=3 col=0
the diagonal is 4
i kind messed up with the loop
this what i write so far

int r_c_sum(int ar[N][N],int row,int col){
int i,j,sum=0;
if(row==0)
for(i=0;i<=N;i++)
sum+=ar[row+1][col+1];
sum+=ar[row][col];
return sum;
}

you're not actually incrementing row and column. You're just adding an offset so it ends up adding the same row and col each iteration.

Say the row = 1 and col = 0.

It's going to add 7, three times, then add 4.

You need to actually increment row and col using the ++ operator.

Also, you need to bounds check the row and col variables, not iterate over the dimension of the matrix, else you'll risk going out of bounds.

row and col start the place where you start summing. If you start row and col at 2 each and iterate over the dimension of N, you'll be trying to sum values that are outside of the matrix.
Last edited on
i succeed to calculat to diagonal in case of row=0 or col=0
i still dont find out how can i sum the diagonal if i get input diffrent than zero

int r_c_sum(int ar[N][N],int row,int col){
int i,j,sum=0;
if(row==0 || col==0){
while((row!=N-1) && (col!=N-1))
sum+=ar[row++][col++];
sum+=ar[row][col];
}

return sum;
}

it workes if row or col = 0
Last edited on
You're doing two summations within the while loop and you should be doing only one.
Last edited on
Topic archived. No new replies allowed.