Michel Tamer
Michel Tamer

Reputation: 341

For loop iterating through table

Say I created a table

char[][] table = new char[5][5];

and that I wanted to iterate it using a for loop for creating a "space."

for (int i = 0; i < table.length; i++)
for (int j = 0; j < table[i].length; j++)
       table[i][j] = ' ';   

In the second line what does the [i] mean in table[i].length? why can't it be just table.length like the first line? Thank

Upvotes: 1

Views: 3352

Answers (2)

kiruwka
kiruwka

Reputation: 9450

Your declaration :

char[][] table = new char[5][5];

is equivalent to :

// declare array of size 5, each element is a reference to one-dimen char[] array
char[][] table = new char[5][]; 

// initialize elements of table array, i.e. each row
table[0] = new char[5];
table[1] = new char[5];
table[2] = new char[5];
table[3] = new char[5];
table[4] = new char[5];

Note: you could have initialized each "row" with arrays of different size, for instance

table[3] = new char[255];

and table[1].length will be 5, while table[3].length will be 255.

These sizes of ["rows"] arrays are independent of "aggregate" array size table.length, therefore you have to loop thru each "row" using size of this "row" array.

Upvotes: 2

Soyhan Beyazıt
Soyhan Beyazıt

Reputation: 81

It is there because you are iterating over two dimensional array. I recommend you to check out two dimensional array.

Upvotes: 0

Related Questions