Given a square matrix of size N×N, calculate the absolute difference between the sums of its diagonals.

Problem Statement
Given a square matrix of size N×N, calculate the absolute difference between the sums of its diagonals.
Input Format
The first line contains a single integer, N. The next N lines denote the matrix's rows, with each line containing N space-separated integers describing the columns.
Output Format
Print the absolute difference between the two sums of the matrix's diagonals as a single integer.
Sample Input
3
11 2 4
4 5 6
10 8 -12
Sample Output
15

Solution:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int a[][] = new int[n][n];
        for(int a_i=0; a_i < n; a_i++){
            for(int a_j=0; a_j < n; a_j++){
                a[a_i][a_j] = in.nextInt();              
            }
        }
       
        int result = 0;
       
       
        for(int i=0;i<n;i++)
            {
            result = result + a[i][i] - a[i][n-i-1];
        }
        System.out.print((result<0)?(-1*result):result);
    }
}

Share on Google Plus

About Admin

Arun is a JAVA/J2EE developer and passionate about coding and managing technical team.
    Blogger Comment
    Facebook Comment

2 comments:

  1. can you explain this
    for(int i=0;i<n;i++)
    {
    result = result + a[i][i] - a[i][n-i-1];
    }

    ReplyDelete
  2. can you explain this
    for(int i=0;i<n;i++)
    {
    result = result + a[i][i] - a[i][n-i-1];
    }

    ReplyDelete