'How do we do sum of indexes in a 2D array
I have a 2D array where rows = 3 and columns = 2. I want to get a sum of all the indices. Here is my array.
arr[][] = [1, 2], [3, 4], [5, 6]
Row 1
At
index (0, 0)the sum of indexes becomes(0 + 0 = 0)At
index (0, 1)the sum of indexes becomes(0 + 1 = 1)Row 2
At
index (1, 0)the sum of indexes becomes(1 + 0 = 1)At
index (1,1)the sum of indexes becomes(1 + 1 = 2)Row 3
At
index (2, 0)the sum of indexes becomes(2 + 0 = 2)At
index (2, 1)the sum of indexes becomes(2 + 1 = 3)
My expected output becomes
0 1 1 2 2 3
I am unable to find any resource, how to do this
Solution 1:[1]
You have to do sum of column and row using for loop or any other loop.
import java.util.*;
public class Main
{
public static void main(String[] args) {
int rows, cols, sumIndex = 0;
int a[][] = {
{1, 2},
{3, 4},
{5, 6}
};
rows = a.length;
cols = a[0].length;
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
sumIndex = i + j;
System.out.print(sumIndex + " ");
}
}
}
}
Solution 2:[2]
Another quick example:
import java.util.*;
class Main {
public static void main(String[] args) {
int[][] arr = new int[3][2];
for(int row=0; row<arr.length; row++) {
for(int col=0; col<arr[row].length; col++) {
arr[row][col] = row + col;
}
}
for(int[] row : arr) {
System.out.println(Arrays.toString(row));
}
}
}
Output:
[0, 1]
[1, 2]
[2, 3]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Idle_Mind |
