| Input1 |
Expected outputs |
mat = { {7,1,4}, {9,0,3}, {2,1,-1}}
|
Sum Of Diagonals: 6
|
mat= { {3,1,-5,6}, {-9,3,2,7}, {-1,0,0,9}, {4,2,6,9}}
|
Sum Of Diagonals: 15
|
| The java method should accept following input parameters: mat (integer matrix).
|
| Initialize a variable sumDiagonal for storing the value of sum of diagonal elements.
|
| Iterate through mat using a for loop, using variable rIdx as loop counter. Loop variable rIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till rIdx < mat.length:
Iterate through mat using a for loop, using variable cIdx as loop counter. Loop variable cIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till cIdx < mat[0].length:
If (rIdx==cIdx):
Set sumDiagonal+=mat[rIdx][cIdx].
|
| Once above loops are completed, return sumDiagonal.
|
Below fully running code can be copied and run on Eclipse or other Java IDEs. Refer the classname in code below. If the class name below is "A", save the code below to a file named A.java before running it.
Be sure to try your own test cases to enhance your understanding !
You can also tweak the code to optimize or add enhancements and custom features.
public class MdArraySumDiagonal {
public int matArraySumDiagonal(int[][] mat) throws Exception{
int sumDiagonal=0;
for (int idx=0; idx < mat.length; idx++) {
sumDiagonal+=mat[idx][idx];
}
return sumDiagonal;
}
public static void main(String[] args) {
MdArraySumDiagonal ap=new MdArraySumDiagonal();
int sumDiagonal;
try {
int[][] arr = { {7,1,4},
{9,0,3},
{2,1,-1}
};
print2dArray(arr, "The 2d Array");
sumDiagonal=ap.matArraySumDiagonal(arr);
System.out.println("\n Sum Of Diagonals: "+sumDiagonal);
int[][] arr1 = { {3,1,-5,6},
{-9,3,2,7},
{-1,0,0,9},
{4,2,6,9}
};
print2dArray(arr1, "The 2d Array");
sumDiagonal=ap.matArraySumDiagonal(arr1);
System.out.println("\n Sum Of Diagonals: "+sumDiagonal);
}catch (Exception exception) {
System.out.print("Exception,"+ exception);
exception.printStackTrace();
}
}
public static void print2dArray(int[][] intArray, String label) throws Exception {
// Case 1: The input Array is null !!
if (intArray == null) { System.out.println("\n\n Input 2d Array was null !! \n"); return; }
// Case 2: Print input Array by index (first to last)
System.out.println();
System.out.println("*********************************************************************");
System.out.print(label+" : \n");
int rIdx=0; int cIdx=0;
for (rIdx=0; rIdx < intArray.length; rIdx++) {
for (cIdx=0; cIdx < intArray[rIdx].length; cIdx++) {
System.out.print(intArray[rIdx][cIdx]);
if (cIdx < intArray[rIdx].length) System.out.print(",");
}
System.out.print("\n");
}
System.out.println();
System.out.println("**********************************************************************");
System.out.println();
Thread.sleep(2000);
return;
}
}