Nested loop to add data to an Array
Solution 1:
This is what I tried, seem it match with your requirement, you can check it.
int arr[][] = new int[10][3];
int i, j;
int value = 21;
for(i =0; i <10;i++) {
for(j = 0; j <3; j++) {
arr[i][j] = value;
}
value +=20;
}
Solution 2:
The formula you are interested in seems to be ((i + 1) * 20) + 1
which will give you the value at the correct zero based index. Like,
int[][] arr = new int[10][3];
for (int i = 0; i < arr.length; i++) {
int c = ((i + 1) * 20) + 1;
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = c;
}
}
System.out.println(Arrays.deepToString(arr));
Outputs (formatted for post)
[[21, 21, 21], [41, 41, 41], [61, 61, 61], [81, 81, 81],
[101, 101, 101], [121, 121, 121], [141, 141, 141],
[161, 161, 161], [181, 181, 181], [201, 201, 201]]
Note we could use Arrays.fill(int[], int)
to fill the array too. Like,
for (int i = 0; i < arr.length; i++) {
int c = ((i + 1) * 20) + 1;
Arrays.fill(arr[i], c);
}