Diagonal Sum of a Matrix


SUBMITTED BY: anilkumarsomasi

DATE: May 2, 2016, 7:14 p.m.

FORMAT: Text only

SIZE: 588 Bytes

HITS: 6994

  1. Diagonal Sum of a Matrix
  2. The following program illustrates Diagonal Sum of given Matrix
  3. public class DiagonalSum {
  4. public static void main(String[] args) {
  5. int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
  6. System.out.println(new DiagonalSum().getDiagonalSum(matrix));
  7. }
  8. public int getDiagonalSum(int[][] matrix) {
  9. int sum = 0;
  10. for (int i = 0; i < matrix.length; i++) {
  11. for (int j = 0; j < matrix[i].length; j++) {
  12. if (i == j) {
  13. sum += matrix[i][j];
  14. }
  15. }
  16. }
  17. return sum;
  18. }
  19. }
  20. Result:
  21. Ouput: 15

comments powered by Disqus