In a square matrix diagonal elements are two type. In case of left diagonal the row number and column number are same. that is row no = col no. And in case of right diagonal row number + column number = (Total row number - 1). Therefore, we just travel the array once and add all the elements which meet the above conditions.
import java.util.*;
public class Diagonal2D
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
int s=0;
int [][]arr=new int[4][4];
for(int r=0;r<4;r++)
{
for(int c=0;c<4;c++)
{
arr[r][c]=sc.nextInt();
}
}
for(int r=0;r<4;r++)
{
for(int c=0;c<4;c++)
{
if((r==c) || (r+c==3))
{
s+=arr[r][c];
}
}
}
System.out.println("Sum Is : " + s);
}
}