Representation of 2D Array
To understand 2D array, lets see how 1D array can be pictorially depicted:
Code:
Dim myArray() As String = {“This”,“Is”,“A”,"Single Dimensional”, “Array!”}
Tabular format:
0 1 2 3 4
“This” “Is” “A” “Single Dimensional” “Array!”
Pictorial Representation of a 2D array:
Columns
R 0 1 2 3 4
o
w 1 “My” “First” “2D” “Array”
s
2 “This” “Is” “Cool” “DS”
3 “CS” “Is” “Awesome” “field!”
4 “I” “love” “CS” “very much!”
Equivalent code:
Dim my2DArray(,) As String = {{"My", "First", "2D", "Array"},
{"This", "Is", "Cool", "DS"},
{"CS", "Is", "Awesome", "field."},
{"I", "love", "CS", "very much!"}}
Or
Dim my2DArray(4,4) As String
my2DArray(0,0) = "My"
my2DArray(0,1) = "First"
my2DArray(0,2) = "2D"
my2DArray(0,3) = "Array"
my2DArray(1,0) = "This"
my2DArray(1,1) = " Is"
1
my2DArray(1,2) = "Cool"
my2DArray(1,3) = "DS"
my2DArray(2,0) = "CS"
my2DArray(2,1) = "Is"
my2DArray(2,2) = "Awesome"
my2DArray(2,3) = "field!"
my2DArray(3,0) = "I"
my2DArray(3,1) = "love"
my2DArray(3,2) = "CS"
my2DArray(3,3) = "very much!"
Accessing 2D array elements
Element in 2D array can be accessed using: my2DArray(nth row, nth column)
Question 1: Access the string: “Awesome” from 2D array implemented in the previous section.
Solution:
It is located at second row and second column. Hence code statement: my2DArray(2,2)
To display it in the console: Console.WriteLine(my2DArray(2,2))
Question 2: Accessing all of the elements and printing them in the console.
Solution: All of elements are accessed by inner and outer loop. Code as follows:
'To access inner array. Inner arrays are treated as rows.
For row = 0 to 3
'To access the element.
For col = 0 to 3
'To print elements of a row within same line followed by a
'separator.
Console.Write(my2DArray(row, col) & " ")
Next
'Once all elements of the row is displayed, we move to the next line
Console.WriteLine()
Next
Output: