2

I am trying to format an array that is the following:

[1] [2] [3] [4] [5]
[6] [7] [8] [9] [10]
[11] [12] [13] [14] [15]

How could I initialize the two dimensional array and the values using nested for loops?

0

2 Answers 2

6

I think you have a misunderstanding of two dimensional arrays. Think of them beeing arrays containing arrays.

if you really want this:

[[1] [2] [3] [4] [5]
[6] [7] [8] [9] [10]
[11] [12] [13] [14] [15]]

You could initialize it like that:

int[][] array2d = new int[15][1]
for (int i = 0; i < array2d.length; i++) {
    array2d[i][0] = i + 1;
}

If in fatc, what you really want is:

[[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[11, 12, 13, 14, 15]]

you could use:

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

3 Comments

I think you could use a third variable, like k, for better understanding of the Original Poster.
Thanks for the answer, do you know how I could then print the array in the order of the columns? Such as: 1 6 11 2 7 12 3 8 13 etc...
@user2057847: Yes, I know. That's a new question. Try something, if you can't figure it out, post a new question containing what you have tried.
1

Try something like:

int width = 5;
int height = 3;
int[][] array = new int[height][width];

for (int i = 0; i < height; i++)
{
    for (int j = 0; j < width; j++)
    {
        array[i][j] = i + j + (width * i);
    }
}

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.