15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Jagged arrays ❘ 133<br />

You can also initialize the two - dimensional array by using an array indexer if you know the value for the<br />

elements in advance. For the initialization of the array, one outer curly bracket is used, <strong>and</strong> every row is<br />

initialized by using curly brackets inside the outer curly brackets.<br />

int[,] twodim = {<br />

{1, 2, 3},<br />

{4, 5, 6},<br />

{7, 8, 9}<br />

};<br />

When using an array initializer, you must initialize every element of the array. It is not<br />

possible to leave the initialization of some values for later.<br />

By using two commas inside the brackets, you can declare a three - dimensional array:<br />

int[,,] threedim = {<br />

{ { 1, 2 }, { 3, 4 } },<br />

{ { 5, 6 }, { 7, 8 } },<br />

{ { 9, 10 }, { 11, 12 } }<br />

};<br />

Console.WriteLine(threedim[0, 1, 1]);<br />

jagged arrays<br />

A two - dimensional array has a rectangular size (for example, 3 3 elements). A jagged array is more<br />

fl ex ibl e i n si z i n g t h e a r r ay. W it h a ja g g e d a r r ay e ve r y row c a n h ave a d i f f e re nt si z e .<br />

Figure 6 - 4 contrasts a two - dimensional array that has 3 3 elements with a jagged array. The jagged array<br />

shown contains three rows where the fi rst row has two elements, the second row has six elements, <strong>and</strong> the<br />

third row has three elements.<br />

Two-Dimensional Array<br />

Jagged Array<br />

1 2 3<br />

1 2<br />

4 5 6<br />

7 8 9<br />

3 4 5 6 7 8<br />

9 10 11<br />

figure 6-4<br />

A jagged array is declared by placing one pair of opening <strong>and</strong> closing brackets after another. With the<br />

initialization of the jagged array, only the size that defi nes the number of rows in the fi rst pair of brackets<br />

is set. The second brackets that defi ne the number of elements inside the row are kept empty because every<br />

row has a different number of elements. Next, the element number of the rows can be set for every row:<br />

int[][] jagged = new int[3][];<br />

jagged[0] = new int[2] { 1, 2 };<br />

jagged[1] = new int[6] { 3, 4, 5, 6, 7, 8 };<br />

jagged[2] = new int[3] { 9, 10, 11 };<br />

code snippet Sample1/Program.cs<br />

Iterating through all elements of a jagged array can be done with nested for loops. In the outer for loop<br />

every row is iterated, <strong>and</strong> the inner for loop iterates through every element inside a row.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!