Question:
Write a program to find the sum of diagonal elements
Program:
1 2 3 4 5 6 7 8 |
a = [[11,2,4],[4,5,6],[10,8,-12]] n=len(a) sumn=0 for i in range(n): for j in range(n): if i+j==n-1: sum+=a[i][j] print (sumn) |
Explanation:
Diagonal elements are those where i=j, as in a[0][0], a[1][1] etc.the for loop cheks every instant if i is equal to j, if true value of a[i][j] is incremented to sum.
Output:
1 |
19 |
Leave a Reply