sum of each diagonal in a matrix | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

sum of each diagonal in a matrix

(incorrect output) how can I find the sum of the primary and secondary diagonal in a matrix? https://code.sololearn.com/ckGB4h7nh1Cg/#java

24th May 2022, 3:26 AM
Eyy
2 Answers
+ 2
For sum of diagonals of square matrices, this will do public class MatrixDiagonalSum { public static void main(String[] args) { int[][] matrix = { { 1, 2, 3 }, { 10, 20, 30 }, { 100, 200, 300 } }; int diagSum1 = 0, diagSum2 = 0; int size = 3, index1 = 0, index2 = size; for( int row = 0; row < size; row++ ) { diagSum1 += matrix[ row ][ index1++ ]; diagSum2 += matrix[ row ][ --index2 ]; } System.out.println( diagSum1 + "\n" + diagSum2 ); } }
24th May 2022, 5:37 AM
Ipang
+ 2
Eyy, for diagonal sum in your code move declaratoon Pd, Sd before first for() add parentheses to second for() so second if() is included in second for() move end of first for() before result display public static void computeSumDia( int[][] num, int[] sum) { int Pd = 0, Sd = 0; //moved here for (int row = 0; row < num.length; row++) { //int Pd = 0, Sd = 0; //move up int col; for (col = 0; col < num[row].length; col++) { //parenthesis if (row == col) Pd += num[row][col]; if ((row + col) == (num.length - 1)) Sd += num[row][col]; } //parenthesis } //parenthesis System.out.println( ... // } //deleted } }
25th May 2022, 7:00 AM
zemiak