Python Program to Find the Sum of a Matrix Diagonal
Beginner · Matrices
A square matrix has two diagonals. The main (principal) diagonal runs from the top-left to the bottom-right, and the secondary diagonal runs from the top-right to the bottom-left. This program prints a 4 x 4 matrix, lists the entries on each diagonal and adds them up.
Program
Matrix: 3 8 1 6 5 2 9 4 7 0 4 2 1 6 3 9 Main diagonal: [3, 2, 4, 9] sum = 18 Secondary diagonal: [6, 9, 0, 1] sum = 16
How it works
- On the main diagonal the row and column numbers are equal, so its entries are
matrix[i][i]. - On the secondary diagonal the column counts down as the row counts up, so its entries are
matrix[i][n - 1 - i]. - One loop over
icollects both diagonals, because each row has exactly one entry on each. - The main diagonal is 3, 2, 4, 9, which adds up to 18, and the secondary diagonal is 6, 9, 0, 1, which adds up to 16.
Other ways to write it
Using i == j and i + j == n - 1
Main diagonal sum: 18 Secondary diagonal sum: 16
The textbook method visits every entry and tests its position: i == j for the main diagonal and i + j == n - 1 for the secondary one.
Both diagonals together, centre counted once
Main: 18 | Secondary: 15 | Both: 28
In a matrix with an odd number of rows, the centre entry lies on both diagonals, so it is subtracted once to avoid counting it twice.
Try it yourself
Change the program to print the sum of the entries above the main diagonal, where j > i.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises