Contenido del Curso
C# Basics
C# Basics
Practicing Multi-Dimensional Arrays
It is sometimes useful to declare constants for indexing multi-dimensional arrays. Following is the array from the last chapter's quiz:
main
We have created two constants FRUITS
and VEGETABLES
with values 0
and 1
, representing the rows 0
for fruits, and 1
for vegetables in the foods
array.
So if we need to access the "Cabbage" element from vegetables, we can simply write:
main
This trick might not be too helpful in smaller arrays like this one itself, however when dealing with more complex arrays, constants like these can help in easily accessing items from the array so that we don't need to memorize which row contains which items - in case we have categorized items in rows.
Now the challenge is to create a 2D array of type string
and name productOptions
, having a 4x3 shape (4 rows, 3 columns). Initialize it with the following data:
Row 1: "Red", "Green", "White" Row 2: "Square", "Rectangle", "Sphere" Row 3: "Thick", "Medium", "Thin" Row 4: "Printed", "Crafted", "None"
Access the "Crafted" element via indexing and output it. Use the relevant constant variable for that.
main
- For declaring a multidimensional array we add commas inside the square brackets (
[]
) depending upon the dimensions of the array. For-example, a 3D integer array would be declared likeint[,,] arrayName = { ... };
. - It is valid to use variable or constant values in indexing.
For-example if we have an array
int[] exampleArray = { 1, 2, 3, 4, 5 };
and a constantconst int someIndex = 2
, it is valid to writeexampleArray[someIndex]
for accessing the element 3 from the Array.
main
¿Todo estuvo claro?