[Solved] 2D Array number grid with for and if


The difference between the two elements in a column is 9: a[i][j] = a[i-1][j] + 9, thus the code may be modified as:

public static void main(String args[]) {
      int array[][] = new int[6][5];
      // initialize the first row
      array[0] = new int[] {1, 2, 3, 5, 7};  
      // print the first row
      System.out.println(Arrays.toString(array[0]));

      for (int i = 1; i < array.length; i++) {
          // populate current row incrementing each element by 9
          for (int j = 0; j < array[i].length; j++) {
              array[i][j] = array[i - 1][j] + 9; 
          }
          System.out.println(Arrays.toString(array[i]));
      }
}

Output:

[1, 2, 3, 5, 7]
[10, 11, 12, 14, 16]
[19, 20, 21, 23, 25]
[28, 29, 30, 32, 34]
[37, 38, 39, 41, 43]
[46, 47, 48, 50, 52]

Update

It would be more interesting task to generate the sequence starting from 1.
Inside the row the differences between two adjacent elements change like 1, 1, 2, 2, 3, and 3 is the difference between the last element of the previous row and the first element in the next row.

int x = 1;
for (int i = 1; i < 7; i++) {
    for (int j = 1; j < 6; j++) {
        System.out.print(x + "  ");
        x += j / 2 + j % 2;
    }
    System.out.println();
}

1

solved 2D Array number grid with for and if