I have two dimensional array
private static int [][] n = {{1, 2, 3, 4}, {5, 6, 7, 8}};
And I have
int m = 3;
How can I multiply each element in my two dimensional array by 3?
So that the output would be like this:
{{3, 6, 9, 12},{15, 18, 21, 24}}
Also, if I had a matrix like
{{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}},
How would I print the diagonal elements?
{1,7,13,19,25} and {5,9,12,17,20}
I'd like to know algorithm, because for multiplying dimensional array I used
private static int[] n = {1, 2, 3, 4, 5, 6, 7};
private static int[] multiply(int[] n, int m) {
int array[] = new int[n.length];
for (int i = 0; i < n.length; i++) {
array[i] = n[i] * m;
}
return array;
}
Just iterate both dimensions:
private static int[][] multiply(int[][] n, int m) {
int array[][] = new int[n.length][];
for (int i = 0; i < n.length; i++) {
array[i] = new int[n[i].length];
for (int j = 0; j < n[i].length; j++) {
array[i][j] = n[i][j] * m;
}
}
return array;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With