Visual Basic Lesson 9:
So, we have gone over one dimensional arrays, which means we are ready to advance onto two dimensional arrays... Exciting right? Obviously, because we have already explored arrays this will build upon the previous lesson more than most.
Once again two dimensional arrays are a type of data structure. You still have to declare variables and all the normal stuff like that. But instead of just having a row of code, you can have rows and columns. That is the essential difference between two dimensional arrays and one dimensional arrays. Otherwise it still stores a collection of the same data type. Two dimensional arrays also have indexes, there are row indexes and column indexes and these are assigned to each array element, as usual. Once again, the elements are initialised to zero until the user inputs data.
The example of a variable declaration for a two dimensional array is:
Dim table(3, 10) As Integer
You specify how much data you are going to store, so how many rows of data and how many columns. Similar to how you would create a table in Microsoft Word.
Once again, loops go well with these data structures; however, generally you use nested For Next Loops with two dimensional arrays.
For example:
The example of a variable declaration for a two dimensional array is:
Dim table(3, 10) As Integer
You specify how much data you are going to store, so how many rows of data and how many columns. Similar to how you would create a table in Microsoft Word.
Once again, loops go well with these data structures; however, generally you use nested For Next Loops with two dimensional arrays.
For example:
For i = 1 to 3
For j = 1 to 10
Table(i, j) = 55
Next j
Next i
The inner loop has to be completed before the outer loop can move on. For example, j needs to go through numbers 1, 2, 3, 4 etc... Before i can equal 2. This is true for all nested loops. This particular set of For Next loops means that for each "turn" the inner loop counts through each element in the row, once it has reached 10, the program moves to the next row. Each element in this program is set to 55.
An example program created in class is:
This program uses a nested For Next loop with a two dimensional array in order to get 25 different pieces of data and create an average for them.
That is essentially two dimensional arrays. See ya next time!
No comments:
Post a Comment