Total Sum on the Boundaries and Diagonals

 

For a given two-dimensional square matrix of size (N x N). Find the total sum of elements on both the diagonals and at all the four boundaries.

Sample input 1:
3 3
1 2 3
4 5 6
7 8 9
Sample Output 1:
45
import java.util.Scanner;

public class SumDiaBound {

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int n = s.nextInt();
		int m = s.nextInt();
		int input[][] = new int[n][m];
		for(int i = 0; i < n; i++)
		{
			for(int j = 0; j < m; j++)
			{
			input[i][j] = s.nextInt();
		}

	}
		totalSum(input);

}

	public static void totalSum(int[][] mat) {

		int s=0;
		for(int i=0;i<mat.length;i++)
		{
			
			for(int j=0;j<mat[i].length;j++)
			{
				if(i==j || i+j==mat.length-1)
				{
					
					s=s+mat[i][j];
				}
				else if(i==0 || i==mat.length-1 || j==0 || j==mat.length-1)
				{
					s=s+mat[i][j];
				}
			}
				
		}

	
	System.out.println(s);
	}

}

Comments

Popular posts from this blog

Minimum Length Word

Check Number Sequence