Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

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?

1 Answer

0 votes
by (13.1k points)

You have used unnecessary print statement 

 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();

    }

Remove them.

Calculate the sums using a single loop:
 

for(int i = 0, j = n - 1; i < n; ++i, j --)

 {

    sum1 += a[i][i];

    sum2 += a[i][j];

  }

System.out.println(Math.abs(sum1 - sum2));

Want to learn Java? Check out the Java certification from Intellipaat.

Related questions

0 votes
1 answer
asked Dec 15, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...