# Find the sum of the diagonal elements of the given matrix

Posted by Chikul under Others category on | Views : 17808
For e.g. you are given a 3 X 3 matrix of integers as

2 5 5
3 7 4
4 2 3

Output is 18

`import java.io.*;import java.lang.*;public class Sum_Diagonal{	public static void main(String args[])throws IOException	{		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));		System.out.println("Enter the size of 2D array :");		int i=Integer.parseInt(br.readLine());		int d[][]=new int[i][i];			int j,k;		int sum1=0,sum2=0;				BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));		System.out.println("Enter the values of 2D array of "+i+" * "+i+" matrix ");				for(j=0;j<i;j++)		{			for(k=0;k<i;k++)			{				d[j][k]=Integer.parseInt(br1.readLine());			}		System.out.println();		}		for(j=0;j<i;j++)		{			for(k=0;k<i;k++)				System.out.print(d[j][k]+" ");				System.out.println();		}				for(j=0;j<i;j++)		{				sum1=sum1+d[j][j];				}		k=i-1;		for(j=0;j<i;j++)		{			if(k>=0)			{				sum2=sum2+d[j][k];				k--;				}		}		System.out.println("Sum of Digonal elements are  :"+sum1+" "+sum2);	}}									 `