+ 1
JAVA: Multidimensional Arrays with For Loops
This code outputs 4 public class Demo { public static void main(String[] args) { int[][] sample = { {1, 2, 3}, {4, 5, 6} }; for(int x=0; x<sample.length; x++) { for(int y=0; y<sample[x].length; y++) { System.out.println(sample[x][y]); } } } } But what happpens in the 2nd for loops here? "for(int y=0; y<sample[x].length; y++) {" sample[x] should only be using one of the 2 dimensions of the array, right? Is it using the row or the column here? Thanks
7 Answers
+ 7
there x represents row value and y represents column values. So
sample[x].length returns x row length
Note that your array is 2x3 matrix. 2 rows and each has 3 columns.
x = 0 =>
sample[0][0]= 1 sample[0][1]= 2 sample[0][2]= 3
x = 1 =>
sample[1][0]= 4 sample[1][1]= 5 sample[1][2]= 6
sample.length returns length of array sample.
+ 5
You can see for yourself the execution of this code:
public class Demo {
public static void main(String[] args) {
int[][] sample = {
{1, 2, 3},
{4, 5, 6}
};
for(int x=0; x<sample.length; x++) {
for(int y=0; y<sample[x].length; y++) {
System.out.println("sample["+x+"]["+y+"] = "+sample[x][y]);
}
}
}
}
+ 4
length property always returns the length of array that is number of elements initialized.
Multidimensional array is always think like array will storing other arrays.. So nested elements, (arrays, or not,) does not matter.
sample.length returns 2.( outer array has 2 elements ie 2 inner arrays). x values will be 0 and 1 only
sample[x].length returns number elements in x row . So both times returns 3 . ( so y will be 0,1,2)
Hope it clears..
+ 3
@Jayakrishna š®š³ Thanks for answering. I have a few more questions, so sample.length returns the length of the array, what is the length of the array? Is it 6? Because there are 6 elements overall.
Another question I had was on the first loop of the for loop x will be zero, so the line in question will be sample[0].length, right? So this means that the program is finding the length of the first row of arrays, correct? Which of course would be 3. Thanks in advance.
+ 2
@Jayakrishna š®š³ @Orin Cook Ok that clears everything up thank you. I will probably have even more questions when and if we reach 3 dimensional arrays but for now it makes sense to me thanks a lot!
+ 1
sample.length returns the number of rows, because sample is an array of arrays, so each subarray is a single element. So sample.length == 2
sample[x].length in turn returns the number of elements in the x-th subarray, which here represents the columns (in row x specifically, which didn't matter here because every row has the same number of columns, but can matter in other cases). So yes to your second question.
+ 1
3D (or even more) just extend the same concepts another level: you just get an array of (array of arrays).