Write a method called sumDiagonal() that takes a 2D array of int as an argument returns the sum of the first element in the first row, the second element of the second row, the third element of the third row, etc. You may assume that the array is not jagged and has at least as many columns as rows.
public class SumDiagonal { public static int sumDiagonal(int[][] m) { int sum = 0; for (int i = 0; i < m.length; i++) { sum += m[i][i]; } return sum; } public static void main(String[] args) { int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; System.out.println("Array is:"); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println("Sum of elements of diagonal is " + sumDiagonal(arr)); } }
Get Answers For Free
Most questions answered within 1 hours.