-1

I am currently working on an online coding class and I am wondering how instead of manually achieving the answer, how can I use a loop to be more efficient because a worksheet has the following question:

Given: int[][] values = new int[4][5]
Write a nested loop to set values as follows:

    [0] [1] [2] [3] [4]
 [0] 1   2   3   4   5
 [1] 1   2   3   4   5
 [2] 1   2   3   4   5
 [3] 1   2   3   4   5

The following code I have is:

int table[][] = new int [4][5];
table[0][0] = 0;
table[0][1] = 1;
table[0][2] = 2;
table[0][3] = 3;
table[0][4] = 4;

table[1][0] = 1;
table[1][1] = 2;
table[1][2] = 3;
table[1][3] = 4;
table[1][4] = 5;

table[2][0] = 1;
table[2][1] = 2;
table[2][2] = 3;
table[2][3] = 4;
table[2][4] = 5;


table[3][0] = 1;
table[3][1] = 2;
table[3][2] = 3;
table[3][3] = 4;
table[3][4] = 5;

table[4][0] = 1;
table[4][1] = 2;
table[4][2] = 3;
table[4][3] = 4;
table[4][4] = 5;

/* System.out.print table */
djm.im
  • 3,295
  • 4
  • 30
  • 45
  • So you already know that you need loops for that. Why haven't you (apparently) started? – akuzminykh Dec 06 '20 at 06:20
  • `for (int i = 0; i < 4; ++i) { for (int j = 0; j < 5; ++j) { table[i][j] = j + 1; } }` Besides _for_ loops there are _while_ and _do-while_ loops. – Joop Eggen Dec 06 '20 at 06:24
  • You don't need loops at all. `int[][] table = {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}};` Take a look on this question https://stackoverflow.com/questions/1938101/how-to-initialize-an-array-in-java – djm.im Dec 06 '20 at 11:41

1 Answers1

1

Note that the value of each element in the inner arrays equal their index + 1, independently from their outer index. Let's apply a nested loop and apply this formula in the inner loop:

for (int i = 0; i < table.length; i++) {
    for (int j = 0; j < table[i].length; j++) {
        table[i][j] = j + 1;
    }
}

Note that we can get the size of an array, this was used in both levels of the loop.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175