R. Lee
R. Lee

Reputation: 63

How to create a matrix using a 2D array

I am trying to create a 6x3 matrix that increases by one each time as you iterate over the column first and the row second.

This is the code, which I currently have:

public static void main(String[] arg) {

    int[][] mat1 = new int[6][3];
    for(int i = 1; i < mat1.length; i++) {
        for(int j = 0; j < mat1[i].length; j++) {
            mat1[i][j] = i + j;
            System.out.print(mat1[i][j] + " ");
        }
        System.out.println();
    }
}

Right now I am getting the output:

1 2 3 
2 3 4 
3 4 5 
4 5 6 
5 6 7 

The desired output is:

1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18

How would I go about doing this?

Upvotes: 1

Views: 76

Answers (2)

Donatic
Donatic

Reputation: 323

The output you get is correct:

On the first iteration, i = 1 and j = 0, so i+j = 1
On the 4th iteration i = 2 and j = 0, so i+j = 2
On the 7th iteration i = 3 and j = 0, so i+j = 3

here is on of the solution for your problem

public static void main(String[] arg) {

  int[][] mat1 = new int[6][3];
  int counter = 1;
    for(int i = 0; i < mat1.length; i++) {
        for(int j = 0; j < mat1[i].length; j++) {
            mat1[i][j] = counter;
            counter++;
            System.out.print(mat1[i][j] + " ");
        }
        System.out.println();
    }
}

Upvotes: 1

GhostCat
GhostCat

Reputation: 140427

You want to generate a "sequence" that counts from 0, 1, 2, .. 17. Your problem is that i+j doesn't generate that sequence.

Therefore:

mat1[i][j] = i + j;

is simply not counting up. A much simpler solution would be this:

mat1[i][j] = overallCounter++;

( and that overallCounter is declared int overallCounter = 0 before the outer for loop ).

side note: and as the comment correctly states: i should start at 0, too. Arrays are 0-based in Java!

Upvotes: 2

Related Questions