How would I add these elements?

I have a 2D array of ints that looks something like this:
[1][2][3]
[4][5][6]
[7][8][9]

I want to add the diagonal values of this matrix (1+5+9 and 3+5+7). How can I do this? The 2D array is arbitrarily large so it doesn't necessarily have to be a 3x3 matrix like in the above example.
Last edited on
1. Determine the smallest dimension of the matrix.
2. Use a FOR loop from zero to the smallest dimension - 1 to accumulate the value of matrix[i][i].
3. For the other diagonal you just use 2 iterator variables in one FOR. Read about the comma operator.

That should do it.
Will the matrix always be square?
Yeah, the matrix will always be a square. So, it will always be of the type NxN where N is any real int.
Hmmm I think I was making it harder than it is. Correct me if I'm wrong but if the matrix is always a square, wouldn't there always only be two diagonals? And wouldn't the indices of the elements in a diagonal always be the same index number? So in a 3x3 matrix, the indices of a diagonal row would be [0][0],[1][1],[2][2], right?
webJ has it.

Something like:

1
2
3
4
5
6
7
8
i_accum = 0;
anti_i_accum = 0;

for( int i = 0, anti_i = matrix_dimension - 1; i < dimension; i++, anti_i-- )
{
    i_accum =+ matrix[i][i];
    anti_i_accum = +matrix[anti_i][anti_i];
}


Something along those lines.

@roberts:

1. Your sums yield the sumation of the same diagonal, meaning you have an error in the algorithm.
2. Don't give out complete coding. For all we know this is homework for the OP. We don't actually DO other people's homework, at least not knowingly. People don't learn if you do.
I was going to suggest that it can be done in one loop, though roberts already tried.

Remember that M[i][i] is the negative diagonal, the positive diagonal is M[i][N-i].

Hope this helps.
Last edited on
Sorry, was damned dumb. I had other thoughts in my head.
The only damned ones are those who never make mistakes. Don't worry about it :-)
Topic archived. No new replies allowed.