Sum Of Trailing Diagonal
Write a program to display the sum of trailing(right) diagonal in a n x n matrix.
import java.io.*;
class SumOfTrailingDiagonal
{
public static void main(String ar[])throws Exception
{
BufferedReader ob=new BufferedReader(
new InputStreamReader(System.in));
int i,j,sopd=0,n;
System.out.println("Enter the no of rows for a square matrix : ");
n=Integer.parseInt(ob.readLine());
int a[][]=new int[n][n];
System.out.println("\nEnter "+(n*n)+" elements : ");
for(i=0;i< n;i++)
{
for(j=0;j< n;j++)
{
a[i][j]=Integer.parseInt(ob.readLine());
}
}
for(i=0;i< n;i++)
{
for(j=0;j< n;j++)
{
if(i+j==n-1)
sopd+=a[i][j];
}
}
System.out.println("\nSum of trailing diagonal : "+ sopd);
}
}
Have something to say? Log in to comment on this post.
0 comments