0

write a program to print and find sum of principal diagonal elements of matrix and also sum of secondary diagonal elements

m=[[1,2,3],[4,5,6],[1,2,3]] sum=0 for i in range (3): for j in range (3): if i=j: sum=sum+m[i][j] print(sum) I wrote this for sum of principal diagonal elements but I am getting error message can u modify the code so that I get the desired result. thanks in advance

28th Nov 2018, 5:15 PM
Mara
2 Answers
+ 2
In if statement write i == j Hope this helpsâ˜șâ˜ș.
28th Nov 2018, 5:59 PM
Meet Mehta
Meet Mehta - avatar
+ 2
You could also do it with just one loop: for i in range(3): sum += m[i][i] Also, since sum() is a built-in function, it may be better to use a different variable name. The term we use in mathematics for the sum of the principal diagonal elements is "trace"; you could use that 😉
28th Nov 2018, 7:09 PM
Kishalaya Saha
Kishalaya Saha - avatar