Square matrices
Let the matrix
A
contain
N
rows and the same number of columns. Such matrices are called
square.
Square matrices have main and secondary diagonals.
Main diagonal - the diagonal that goes from the top left corner to the bottom right corner.
Side diagonal- goes from upper right corner to lower left corner.
Then, to iterate over all elements on the main diagonal, one loop is enough:
pseudocode:
for i from 0 to N-1
working with A[i][i]
The same loop can iterate over the elements of the secondary diagonal.
For elements on the side diagonal, the sum of the row and column indices is constant and equals N-1
.
pseudocode:
for i from 0 to N-1
working with A[i][N-1-i]
To process all elements located on the main diagonal and below it, you need a nested loop:
- line number changes from
0
to
N-1
;
- column number from
0
to
i
.
pseudocode:
for i from 0 to N-1
for j from 0 to i
working with A[i][j]