I have a problem with an (I guess) simple Java program. I need to create a two-dimensional array (that is called a “matrix”, right?) which should look like this:
1 2 3 4 5 6 7 8 9 10 (1st row)
3 4 5 6 7 8 9 10 11 12 (2nd row)
6 7 8 9 10 11 12 13 14 15 (3rd row)
...
As you can see, the 1st row is 1, 2, 3, …; the 2nd row is the 1st row with the 2nd row’s row index added to each element. And so on: Every row is the previous row + the current row’s row number (1-based).
First define the number of columns and rows, and instantiate the array:
Then do a loop for every row, and inside that loop, loop for every column, let’s say you call the outer loop counter
iand the inner loop counterj. Then you can assign a value in the array using this formula:This formula assumes
0 <= i < rowsand0 <= j < columns