简体   繁体   中英

Initialize 2D array using nested for loops and finding a pattern

I'm trying to figure out how nested for loops for initializing variables work. I looked at another question on here that initialized values in a 2D array from 1 to 15 which seemed reasonable using the code:

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

I'm trying to extend that idea so that another array has the pattern as follows:

 {0, 9,18,27,36,45,54,63,72} //row0...row8
 { 1,10,19,28,37,46,55,64,73}

It obvious that once a row completes a number is incremented by 1 and you keep adding 9 until you get to the end of the row. How is this represented in code? Solution to this problem would be great but a more general approach would be appreciated more if possible. My guess is that the headings for the for loop statements don't change but rather its the assignment equation that does.

Would this work?

for(int i=0; i < 9; i++){
  for(int j=0; j < 9; j++){
    row[i][j] = j+i;
  }
}
for (int i = 0; i < row.length; i++) {
    for (int j = 0; j < row[j].length; j++) {
        row[i][j] = i + j * 9;
    }
}

Have a try with the following code:

    int[][] row = new int[9][9];
    for (int i = 0; i < row.length; i++) {
        row[i][0] = i;
        for (int j = 1; j < row[i].length; j++) {
            row[i][j] = row[i][j - 1] + 9;
        }
    }

    /*
     * Print 2d-array
     */

    for (int i = 0; i < row.length; i++) {
        for (int j = 0; j < row[i].length; j++) {
            System.out.printf("%2d ", row[i][j]);
        }
        System.out.println();
    }

Output in Console:

 0  9 18 27 36 45 54 63 72 
 1 10 19 28 37 46 55 64 73 
 2 11 20 29 38 47 56 65 74 
 3 12 21 30 39 48 57 66 75 
 4 13 22 31 40 49 58 67 76 
 5 14 23 32 41 50 59 68 77 
 6 15 24 33 42 51 60 69 78 
 7 16 25 34 43 52 61 70 79 
 8 17 26 35 44 53 62 71 80 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM