In Java, Print Diagonal Sum Of 2D Matrix
public class Diagonal{
public static void printSum(int [][]matrix){
int primary = 0;
int secondary = 0;
for(int r = matrix.length-1, p = matrix[r].length-1, s = 0; 0 <= r; r --, p --, s++){
primary += matrix[r][p];
secondary += matrix[r][s];
}
System.out.println("Primary diagonal: " + primary);
System.out.println("Secondary diagonal: " + secondary);
}
public static void main(String[]args){
int [][]given = {
{2, 33, 4, 1},
{3, 44, 3, 12},
{56, 7, 8, 86},
{5, 2, 4, 21}
};
printSum(given);
}
}
Comments
Post a Comment