1

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?

2
  • 1
    Why doesn't the outer loop start at int i = 0 ? Your output is currently missing a row. Commented Aug 23, 2018 at 7:24
  • I appreciate the quick accept. And: a really nice question here. All details, expected input output, excellent! Commented Aug 23, 2018 at 7:34

2 Answers 2

2

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!

Sign up to request clarification or add additional context in comments.

3 Comments

@R.Lee The overallcounter is the best solution here. If you have doubts with calculations in loops, then write down the steps on paper to understand them. Yours would be like 1+0 1+1 1+2; 2+0 2+1 2+2; 3+0 3+1 3+2; ....
Thank you for this explanation. @GameDroids thank you for the great advice. I will make sure to do that.
And just for the record: that overall counter also tells you how you can map a NxM twodim array as 1 dim array. Meaning: in the end, having one index going from 0 to 17 ... is "the same" has having two indexes 3 x 6 ;-)
1

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(); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.