0

I'm trying to figure out how nested for loops for initializing variables work. I looked at another question on here that initialized values in a 2D array from 1 to 15 which seemed reasonable using the code:

 for (int i = 0; i < row.length; i++) {
        for (int j = 0; j < row[0].length; j++) {
            row[i][j] = (i * row[0].length) + j;
        }
    }

I'm trying to extend that idea so that another array has the pattern as follows:

 {0, 9,18,27,36,45,54,63,72} //row0...row8
 { 1,10,19,28,37,46,55,64,73}

It obvious that once a row completes a number is incremented by 1 and you keep adding 9 until you get to the end of the row. How is this represented in code? Solution to this problem would be great but a more general approach would be appreciated more if possible. My guess is that the headings for the for loop statements don't change but rather its the assignment equation that does.

3 Answers 3

1
for (int i = 0; i < row.length; i++) {
    for (int j = 0; j < row[j].length; j++) {
        row[i][j] = i + j * 9;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I'm curious. Can I just flip the j and i in row[i][j] = ... to make it row[j][i]=...? I get the answer I want but would this make any difference in the long run?
It depends what you are flipping... if you mean j + i * 9, you can certainly do that.
Yeah, I really should think more before posting on here sigh... Thank you for your response.
1

Would this work?

for(int i=0; i < 9; i++){
  for(int j=0; j < 9; j++){
    row[i][j] = j+i;
  }
}

1 Comment

it doesn't, I apologize.
1

Have a try with the following code:

    int[][] row = new int[9][9];
    for (int i = 0; i < row.length; i++) {
        row[i][0] = i;
        for (int j = 1; j < row[i].length; j++) {
            row[i][j] = row[i][j - 1] + 9;
        }
    }

    /*
     * Print 2d-array
     */

    for (int i = 0; i < row.length; i++) {
        for (int j = 0; j < row[i].length; j++) {
            System.out.printf("%2d ", row[i][j]);
        }
        System.out.println();
    }

Output in Console:

 0  9 18 27 36 45 54 63 72 
 1 10 19 28 37 46 55 64 73 
 2 11 20 29 38 47 56 65 74 
 3 12 21 30 39 48 57 66 75 
 4 13 22 31 40 49 58 67 76 
 5 14 23 32 41 50 59 68 77 
 6 15 24 33 42 51 60 69 78 
 7 16 25 34 43 52 61 70 79 
 8 17 26 35 44 53 62 71 80 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.