I want to find the difference between the sum of two opposite diagonals of a matrix. This is my code:
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
int N=scn.nextInt();
int diag1=0;
int diag2=0;
int[][] matrix=new int[N][N];
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
matrix[i][j]=scn.nextInt();
System.out.print(" ");
}
System.out.println();
}
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
if(i==j)
diag1+=matrix[i][j];
//System.out.println(diag1);
}
}
int counter1=0, counter2=N-1;
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
if(i==counter1 && j==counter2){
diag2+=matrix[i][j];
counter1++;
counter2--;
}
}
}
System.out.println(diag1); // used this for checking purpose
System.out.println(diag2); // used this for checking purpose
System.out.println(Math.abs(diag1-diag2));
This is working but not satisfying all the test cases. Can someone help me with this?