Given a square matrix m3x3 create a java code to calculate t
Given a square matrix m[3x3], create a java code to calculate the value of its SECONDARY Diagonal. See example below.
Example given matrix m[3x3] shown below:
Secondary Diagonal (generic m[3x3]) = m[0,2] + m[1,1] + m[2,0]
Secondary Diagonal (as in the example above) = 11 + 8 + 2 = 21
Note 1: Your java code MUST be GENERIC to calculate the secondary diagonal of ANY square matrix [2x2], [3x3],[4x4], etc. (Use a constant in your code to set the values of numberOfRows and numberOfColumns of your matrix.
Note 2: Your matrix m may be hardcoded (no need of user interaction)
Note 3: In case numberOfRows and numberOfColumns ar differents, your program must display the following message: “This is not a square matrix.”
| (0,0) (0,1) (0,2) | | | 10 12 11 |
| (1,0) (1,1) (1,2) | | | 9 8 31 |
| (2,0) (2,1) (2,2) | | | 2 16 24 |
Solution
public class Test{
public static void secDiag(int matrix[][]){
for(int i = 0; i < matrix.length; i++){
if(matrix.length != matrix[i].length){
System.out.println(\"This is not a square matrix.\");
return;
}
}
int sum = 0;
for(int i = 0; i < matrix.length; i++){
sum += matrix[i][matrix.length - i - 1];
}
System.out.println(\"Secondary Diagonal = \" + sum);
}
public static void main(String args[]){
int arr[][] = {{10, 12, 11}, {9, 8, 31}, {2, 16, 24}};
secDiag(arr);
}
}
![Given a square matrix m[3x3], create a java code to calculate the value of its SECONDARY Diagonal. See example below. Example given matrix m[3x3] shown below: S Given a square matrix m[3x3], create a java code to calculate the value of its SECONDARY Diagonal. See example below. Example given matrix m[3x3] shown below: S](/WebImages/14/given-a-square-matrix-m3x3-create-a-java-code-to-calculate-t-1018385-1761526443-0.webp)