Square Matrix – Corner Elements Sum

              Square Matrix - Corner Elements Sum


A square matrix of size N×N is passed as the input. The program must calculate and print the sum of the elements in the corners.
Input Format:
The first line will contain the value of N.
The next N lines will contain the N values separated by one or more spaces.
Output Format:
The first line will contain the integer value denoting the sum of the elements in the corners.
Boundary Conditions:
2 <= N <= 20
Example Input/Output 1:
Input:
3
10 90 1
4  22 5
32 8 66
Output:
109
Explanation:
The sum = 10+1+66+32 =  109
Code:
import java.util.*;
public class Hello {
    public static void main(String[] args) {
                   Scanner sc=new Scanner(System.in);
                   int i,j,n,sum=0;
                   n=sc.nextInt();
                   int[][] arr=new int[n][n];
                   for(i=0;i<n;i++)
                       {
                          for(j=0;j<n;j++)
                           {
                               arr[i][j]=sc.nextInt();
                              if((i==0&&j==0)||(j==0&&i==n-1)||(i==0&&j==n-1)||(i==n-1&&j==n-1))
                                   sum+=arr[i][j];
                           }
                       }
    System.out.print(sum);
          }
}

Please do comment If u have any Queries!

Add a Comment

Your email address will not be published. Required fields are marked *