# Question about a 2d array example

• 06-06-2011, 07:35 PM
Question about a 2d array example
Hi, I have a question about this little code example. Its always these little nested for loop tricks that mess me up! LOL. Hopefully I will get used to them. But below, I have the following questions about it. The code outputs a table of 0-9 in the top row, then the next row 10-19, etc, there are 5 rows total. My questions are commented on the code lines. Any help greatly appreciated. Thank you!

Code:

```//******************************************************************** //  TwoDArray.java      Author: Lewis/Loftus // //  Demonstrates the use of a two-dimensional array. //******************************************************************** public class TwoDArray {   //-----------------------------------------------------------------   //  Creates a 2D array of integers, fills it with increasing   //  integer values, then prints them out.   //-----------------------------------------------------------------   public static void main (String[] args)   {       int[][] table = new int[5][10];       // Load the table with values       for (int row=0; row < table.length; row++) // table array is 2D, how do get a length for it?         for (int col=0; col < table[row].length; col++)//I don't understand table[row].length.             table[row][col] = row * 10 + col; //I don't understand this.       // Print the table       for (int row=0; row < table.length; row++)       {         for (int col=0; col < table[row].length; col++)             System.out.print (table[row][col] + "\t");         System.out.println();       }   } }```
• 06-06-2011, 07:36 PM
Toll
Look at it as an array of arrays. So table[0] is itself an array, and any array methods can be used on it. That should hopefully make it easier to understand.
• 06-06-2011, 07:43 PM
Thank you Toll. Does table.length refer to 5 elements always in this example please?
• 06-06-2011, 07:48 PM
Toll
Correct. table is an array with length 5; the only special thing about it is that the elements in the array are arrays as well.
• 06-06-2011, 08:10 PM
Great. Just one more question I think. I don't understand this code part.

Code:

`table[row][col] = row * 10 + col;`
It looks like it multiplies row times 10, so it would be counting by 10's or something, but the code outputs in regular sequence. 1 2 3 4 ....
• 06-06-2011, 08:14 PM
Toll
Step through the loop one step at a time.
Code:

```      for (int row=0; row < table.length; row++)         for (int col=0; col < table[row].length; col++)             table[row][col] = row * 10 + col;```
The first time it sets the value, what are the values of row and col? What is the resulting value?
• 06-06-2011, 11:41 PM