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
2 Respostas
+ 2
In if statement write
i == j
Hope this helps☺️☺️.
+ 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 😉