Python program to Sum Diagonals of a Matrix

from random import random
row = 5
matrix = []
for i in range(row):
 myrow = []
 for j in range(row):
    myrow.append(int(random()*10))
 matrix.append(myrow)
for myrow in matrix:
 print(myrow)
sum_diagonal1 = 0
sum_diagonal2 = 0
for i in range(row):
 sum_diagonal1 += matrix[i][i]
 sum_diagonal2 += matrix[i][row-i-1]
print('Sum of first diagonal:',sum_diagonal1)
print('Sum of second diagonal:',sum_diagonal2)

 

 

 

Output:

[4, 4, 2, 5, 6]
[2, 3, 8, 8, 5]
[2, 0, 6, 9, 1]
[0, 3, 0, 6, 8]
[8, 2, 8, 0, 1]
Sum of first diagonal: 20
Sum of second diagonal: 31

 

Subscribe For Daily Updates

100+ Python Pattern Examplespython pattern examples - star patterns, number patterns