Skip to main content

APIzation: Replication Package

[Q#11243774][A#11243868] how to automatically populate a 2d array with numbers

https://stackoverflow.com/q/11243774

Hi i am trying to auto populate a 2d array based on user input. The user will enter 1 number, this number will set the size of the 2d array. i then want to print out the numbers of the array. for example , if the user enters the number 4 . the 2d array will be 4 rows by 4 colums, and should contain the number 1 to 16, and print out as follows. But i am struggling to think of the right statement that will do this. for the moment my code just prints out a 2d array containing *. Has anyone any ideas how i could print out the numbers , i'm really stuck. my code follows:

Answer

https://stackoverflow.com/a/11243868

Read n value,

APIzation

int[][] arr = new int[n][n];
int inc=1;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
arr[i][j]=inc;
inc++;
}
package com.stackoverflow.api;

public class Human11243868 {

  public static int[][] populateMatrixWithNumbers(int n) {
    int[][] arr = new int[n][n];
    int inc = 1;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        arr[i][j] = inc;
        inc++;
      }
    }
    return arr;
  }
}

package com.stackoverflow.api;

/**
 * how to automatically populate a 2d array with numbers
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/11243868">https://stackoverflow.com/a/11243868</a>
 */
public class APIzator11243868 {

  public static void populateArray(int n) throws Exception {
    int[][] arr = new int[n][n];
    int inc = 1;
    for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) {
      inc++;
    }
  }
}