Let assume we have an array of size 3 by 3 means 3 rows and columns

example

1 2 3 4 5 6 7 8 9

In this tutorial, we will learn about how to get the sum of elements that are placed in a different scenarios like the sum of elements in diagonal, last rows, last columns, and so on.

## Sum of left diagonal elements

var i,j,s; s=0; for(i=0; i<2; i=i+1){ for(j=0; j<2; j=j+1){ if(i==j){ s=s+x[i][j]; } } } document.write("Sum of left diagonal elements of a matrix:"+s+"<br>");

## Sum of right diagonal elements

var i,j,s; s=0; for(i=0; i<2; i=i+1){ for(j=0; j<2; j=j+1){ if(i+j==2){ s=s+x[i][j]; } } } document.write("Sum of right diagonal elements of a matrix:"+s+"<br>");

## Sum of lower elements of diagonal in a matrix

var i,j,s; s=0; for(i=0; i<2; i=i+1){ for(j=0; j<2; j=j+1){ if(i>=j){ s=s+x[i][j]; } } } document.write("Sum of lower elements of left diagonal of a matrix:"+s+"<br>");