programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

Iterating through 2-D Arrays

Ranch Hand
Posts: 35
Hi, I have a few questions about multi-dimensional arrays. When iterating through a 2-D Array, such as the code show below here, why do you need to specify "grid[row].length" for the for loop for the column (col) array? Why is this statement written this way? How does this work? I can't seem to wrap my head around this part. I thought the outer for loop in this code has already iterated through the elements of the row part of this array?

Rancher
Posts: 784
19
In your example grid[row] says what row you are on, and the ".length" tells you how many elements are in that row. Instead of putting a constant there, if you use the length property, you can reuse the same code for many different arrays of diverse sizes.

Timothy Han
Ranch Hand
Posts: 35
Why do I need it to tell me what row I'm on? I thought all I should care about is that it iterates through the row and column of this array?

Bartender
Posts: 600
9
The outer loop iterates through the rows, and the inner loop iterates through the columns of each row. You could do it the other way if you wanted - the outer loop iterating through the columns and the inner loop through the rows.

And what if you want to iterate through the rows only, doing something for each row? Or the columns only?

Or consider a 10-dimensional array. If the iteration goes through all cells, what order of the dimensions should it do?

Saloon Keeper
Posts: 4067
48
• 1
In Java, there is technically no such thing as a 2 dimensional array. Java only has arrays of arrays. In your example there are three rows: grid[0], grid[1], and grid[2]. You have a different column count in each row, so therefore, you need the column count of the row you are currently iterating through, hence, grid[row].length.

Timothy Han
Ranch Hand
Posts: 35
Thank you all for clarifying this concept for me.

Marshal
Posts: 5593
384
Just to be sure you fully understand. I think would be easier for you to see it, if you were have an array like this (this snippet wouldn't compile with those row and col, it is just for demonstration):
When you write your inner loop
you prevent index to go out of bounds, because amount of elements on each row differs.

Timothy Han
Ranch Hand
Posts: 35
Thank you Liutaurus, this example reinforces the idea.

 Consider Paul's rocket mass heater.