Menu Close

Sum of diagonal of a matrix in Java …FTC

Write a program to accept a n X n matrix and print addition of diagonal elements of that matrix.

Input:
size of matrix nxn:  2
Enter the matrix:  
1  2 
3  4

Output:
Matrix:  
1  2 
3  4 
Sum of Diagonals:  5
import java.io.*;
import java.util.*;
public class temp {
  public static void main(String[] args) {
    int n,sum = 0;
    Scanner scan = new Scanner(System.in);

    System.out.println("Enter the size of matrix nxn n:  ");
    n = scan.nextInt();
    int[][] matrix = new int[n][n];
    System.out.println("Enter the nxn matrix:  ");
    for(int i=0;i<n;i++){
      for(int j=0;j<n;j++){
        matrix[i][j] = scan.nextInt();
        if(i==j){
          sum += matrix[i][j];
        }
      }
    }

    System.out.println("\nMatrix:  ");
    for (int i=0; i<n; i++){
      for(int j = 0;j<n;j++){
        System.out.print(matrix[i][j]+" ");
      }
      System.out.println();
    }
    System.out.println("Sum of Diagonals:  "+sum);
  }
}

INPUT_1:
Enter the size of matrix nxn n:
3
Enter the nxn matrix:
1  2  3
4  5  6
7  8  9

OUTPUT:
Matrix:
1  2  3
4  5  6
7  8  9
Sum of Diagonals:  15


INPUT_2:
Enter the size of matrix nxn n:
2
Enter the nxn matrix:
1  2  3  4

OUTPUT:
Matrix:
1  2
3  4
Sum of Diagonals:  5


INPUT_3:
Enter the size of matrix nxn n:
4
Enter the nxn matrix:
1  2  3  4
4  8  9  6
2  5  4  8
1  1  1  1

OUTPUT:
Matrix:
1  2  3  4
4  8  9  6
2  5  4  8
1  1  1  1
Sum of Diagonals:  14


INPUT_4:
Enter the size of matrix nxn n:
3
Enter the nxn matrix:
2  2  2  2  2  2  2  2  2

OUTPUT:
Matrix:
2  2  2
2  2  2
2  2  2
Sum of Diagonals:  6


ILLUSTRATION

Executed using javac in Linux Terminal