Wednesday 25 January 2017

To Find The Absolute Difference of the sums of two diagonals of the square matrix

Question:

To Find The Absolute Difference of the sums of two diagonals of the
square matrix

source code:


import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt(); long sum1=0,sum2=0;
        int arr[][]=new int[n][n];
        for(int i=0;i<n;i++)
            {
            for(int j=0;j<n;j++)
                {
                arr[i][j]=sc.nextInt();
                if(i==j)
                {sum1+=arr[i][j];}
                if(j==n-1-i)
                { sum2+=arr[i][j];}
         
            }
        }
     
     
        System.out.println(Math.abs(sum1-sum2));
     
    }
}


In example given below the sum of first diagonal is 17 and second diagonal is 63.
hence printed result would be |sum1-sum2|.











No comments:

Post a Comment