0

JAVA: Diagonal value multiplication

https://code.sololearn.com/ct5QVOzOTG1D This code takes the size of the 2D matrix n and a 2D array of values n*n. It is supposed to print the results of multiplying the numbers on each diagonal together. But my code displays a single value repeated 3 times instead, and I can't find my mistake. Sample input: 3 1 2 3 4 5 6 7 8 9 Sample output: 3 25 63 Explanation: 1 2 3 4 5 6 7 8 9 1*3 =3 5*5 =25 7*9 =63 My output: 63 63 63 Any help is appreciated!

6th Jan 2022, 3:05 PM
Salma D. Elabsi
Salma D. Elabsi - avatar
3 odpowiedzi
6th Jan 2022, 3:50 PM
A͢J
A͢J - avatar
+ 5
Here I have a preloaded matrix just for an example, and the main logic is in the for...loop. You are welcome to confirm in case of any doubt, but I guess you'll get it no sweat ... public class DiagonalSum { public static void main(String[] args) { int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int size = 3; // matrix size for( int left = 0, right = size - 1; left < size; left++, right-- ) { System.out.printf( "%d x %d = ", arr[ left ][ left ], arr[ left ][ right ] ); System.out.println( arr[ left ][ left ] * arr[ left ][ right ] ); } } }
6th Jan 2022, 3:38 PM
Ipang
+ 2
Thank you so much Ipang and AJ! I appreciate it a lot
6th Jan 2022, 4:36 PM
Salma D. Elabsi
Salma D. Elabsi - avatar