In this question, we asked you how to get the sum of the right diagonal of the Matrix.
For Example: we have a 3x3 Matrix:-
1 2 3
4 5 6
7 8 9
Sum of the Right is 15. How to do this in java code.
public static void main(String[] args) {
int[][] array = {
{1,2,3,10},
{3,4,5,10},
{7,5,9,5},
{5,8,9,5}
};
CodePudding user response:
You need to go thtow all rows and sum one number from each row. From the end of the row.
int i= array.length-1;
int sum=0;
for (int j = 0; j < i; j ) {
sum =array[j][i-j];
}
CodePudding user response:
You can do it like this
int[][] array = {
{1,2,3,10},
{3,4,5,10},
{7,5,9,5},
{5,8,9,5}
};
System.out.println(sumRightDiagonal(array));
prints
25
- Get the right most column of the first row.
- initialize the sum to
0
- iterate over the rows of the matrix.
- add current column of row to sum and decrement column
- return the sum when done.
public static int sumRightDiagonal(int[][] mat) {
int sum = 0;
int col = mat[0].length-1;
for (int[] row : mat) {
sum = row[col--];
}
return sum;
}