简体   繁体   中英

Square matrices

I need to write a program that should output the below when Rows and Columns are entered by the user. Example below is for 4x4 matrix:

1   5   9   13

2   6   10  14

3   7   11  15

4   8   12  16

Still a beginner and find those arrays really hard.

It works with the code below, but I'm not sure if it's allowed to fill in like this - columns and then rows.

I was not able to find a way to work with:

for (int i = 0; i < rows; i++){

    for (int j = 0; j < columns; j++){

Code I used:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter your array rows: ");
    int rows = scanner.nextInt();

    System.out.println("Please enter your array columns: ");
    int columns = scanner.nextInt();

    int[][] array = new int[rows][columns];

    int counter = 0;
    for (int j = 0; j < columns; j++){
        for (int i = 0; i < rows; i++) {
            counter++;
            array[i][j]=counter;
        }
    }

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            System.out.print(array[i][j] + " ");
        }
        System.out.println();
    }
}

The trick you want to use here is to use a function to caluclate the value of a given cell. The function is relatively easy.... for each row, the values increase by the number of rows. For example, there are 4 rows, so the values in each row increase by 4..... 1, 5, 9, 13, ....

So, your code can be reduced to just:

for (int r = 0; r < rows; r++) {
    for (int c = 0; c < columns; c++) {
        System.out.print((r + 1 + (c * rows)) + " ");
    }
    System.out.println();
}

No need for any arrays, or temp storage, etc.

to reiterate, the value for each cell is the row (starting from index 1, not 0) plus the "offset" based on the column number (0-based).

You can see it running here: http://ideone.com/RqPgbN

There is no problem filling in the array the way you are doing it, it is perfectly legal. Filling it in rows-first would not make any real difference.

If you really wish to do it rows-first, the following is one way:

int[][] array = new int[rows][columns];
for(int i = 0; i < rows, i++) {
    for(int j = 0; j < columns; j++) {
        array[i][j] = j * rows + i + 1;
    }
}

Just try this code:-

int counter = 0;
    for (int j = 0; j < rows; j++){
        for (int i = 0; i < columns; i++) {
int temp = scanner.nextInt();
            array[i][j]=temp;
        }
    }

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            System.out.print(array[i][j] + "\t");
        }
        System.out.println();
    }

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