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.
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.
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?
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.