View Single Post
 
Old 03-04-2003, 12:21 PM
loquin's Avatar
loquin loquin is offline
Google Hound

Retired Moderator
* Guru *
 
Join Date: Nov 2001
Location: Arizona, USA
Posts: 12,400
Default You can call me arRay...

In VB, Array is not a beam of sunshine. Arrays are just a way of grouping identical types of variables under a common name. Suppose you want to hold the top 10 high scores for a game. You could define an array as
Code:
Dim intHiScoreArray(9) as Integer
"Wait a minute!," you're saying. "Didn't he just say 10 high scores?" Well, yes, but by default, arrays start numbering at 0, not 1. So, 0 through 9 is actually 10 elements. (To further confuse things, VB will allow you to change the default low array element number to one instead of zero – just add the statement “Option Base 1” at the beginning of the form or module. However, for this installment, I’m assuming Option Base 0)

To save a value into this array, you just need to access the variable name, as with any other variable. However, since you also need to specify which of the 10 elements you need, the array element number is also required. Let's say you need to update the 7th array element. You would do so like this:
Code:
intHiScoreArray(6) = 17300

To list all the values in the array, you could refer to every array element individually, but this sort of code is pretty inefficient, and gets very tedious. I would suggest using a loop and just iterate through all the array elements. (see the installment above for a discussion of looping)
Code:
Dim N as Integer For N = 0 to 9 Me.Print intHiScoreArray(N) next N

That’s all there is to it! Arrays are just a piece of cake…

When defining arrays, you may specifically define the upper and lower bound for the array. Lets say you want to create an array of integers with elements from 100 to 200, inclusive.
Code:
Dim intMyArray (100 to 200) as Integer

Now, lets assume that we’re working on the best crossword puzzle program since Henry Ford introduced the Edsel! You are going to display the crossword in full black and white. So, how are you going to keep track of what letters go into which squares? Well, since this article is all about arrays, you’ve probably guessed that we’ll store those letters in an array. Very astute of you! But, since crossword puzzles have letters running both horizontally AND vertically, how do we handle that? Lets define a two-dimensional array. For the moment, we’ll say that the crossword can be no larger than 15 squares wide by 15 squares high, so, we define our array as
Code:
Dim strXWordArray (14,14) As String
That’s it! You’ve just created an array to hold 225 strings (15*15.) To write the words VISUALBASIC (down) into column 8, starting at row 4:
Code:
Dim strWord as String Dim N as Integer strWord = "VISUALBASIC" For N = 3 to 3 + Len(strWord) StrXWordArray (7,N) = Mid$(strWord, N+1, 1) Next N
There’s no real hard and fast rules, in an array definition, as to which array element comes first – just pick one, but (most importantly) stick with the convention that you pick. Since most two dimensional convention is to specify X (or horizontal displacement) first, then Y, you might wish to stay with this.

Can you carry array dimensioning further? Sure. Just define the number of dimensions that your array must hold. Suppose you have an array of elevations for a river delta that changes over time. (Which they do) This array is an xyz plot, with the z (elevation above sea level) quantity being a double. Furthermore, the area you’re storing is a 10 kilometer by 10 kilometer grid, your measurements are 100M apart, and you need to store the data from the last 10 years, in addition to the base reading. Since we have edges (boundries) to include, the array would defined as:
Code:
Dim dblElevations (100, 100, 10) As Double
For our example, we could define the first dimension as the East-West displacement, with 0 being the western boundary of our “map”, the second dimension being the North-South displacement, with 0 being the southern boundary, leaving the third dimension as time, with 0 being the base elevation measurement from at least ten years ago. This leaves us with the vertical displacement, or elevation being the actual data stored in the array. To see the elevation of a point 3.7 Km from the western boundary, 4.2 Km north of the southern boundary, 7 years after we started keeping the data, you would refer to dblElevations(37,42,7)

OK. This is as far as I’ll go for now with multi-dimensional array definition. Now, lets take a look at Dynamic arrays. First, a dynamic array is an array whose dimensions are not defined at compile time, but is instead defined at run time. This means that you don’t have to worry about reserving enough space to hold every element that you might need to store. Instead, you can define an “empty” array of whatever type you need, then change the size to fit your needs when the app runs. Wow! To do this, simply define an array, as we did earlier, but leave the quantity blank:
Code:
Dim strLineArray () as String ' ' Here we define the size ReDim strLineArray(200)
“Now I know what to do! Never assign a fixed array – always make it dynamic! My troubles are solved!” Well, maybe not. As with most decisions, there are trade-offs to consider. Having a fixed array can be expensive in terms of memory requirements – you have to define the array size up front, and the memory requirements are fixed for the life of the array. However, Dynamic arrays, while they use only the amount of memory that you specify at run-time, are “expensive” to create in terms of CPU processing time, and are especially processor intensive if you wish to retain the data that is already in an array (more on this later.) As with many other programming decisions, your decision is really one of a trade-off between size and speed. If you have a well-defined quantity of items to store, or the speed of the application is critical, use a fixed array. If you won’t know how many items you need to store, then make the array dynamic.

If you decide to use dynamic arrays, there are some techniques that may help speed up your processing. Suppose, for instance, that you’re reading lines from a text file, and you know that there will usually be at least 100 lines in the file, but the upper limit could be almost anything. When your app starts, ReDim the array to 100 elements. This means the first 100 reads will take place fairly quickly. But, we’ll need to keep track of how full the array is, so we must increment a counter whenever we read a line from the file.

If we’ve filled up the array, THEN we re-size it. But, not just one new element at a time. Let’s add 100 new elements every time. Keeping space down is important. However, a hundred empty strings don’t take that much more space in memory, but reDimming a 100 extra elements takes little longer than reDimming one extra element. Our code for reading the file would look something like this:
Code:
Const intChunkSize as Integer = 100 Dim strLines () as string ' The array for our text lines Dim lngFileCount as Long ' The file counter Redim strLines (intChunkSize) ' Set the initial array size lngFileCount = 0 Open "C:\MyTextFile.Txt" for Input as #1 Do While Not EOF(1) If lngFileCount = Ubound(strLines) then ' See if we have enough space ReDim Preserve strLines (lngFileCount + intChunkSize) ' Increase array size End If Line Input #1, strLines(lngFileCount) ' Read the line from the file LngFileCount = lngFileCount + 1 ' and increment the line counter Loop Close #1
That’s it. On average, you’ll have 50 spare array elements when you’re through reading the file. Note a couple of things in the above example: First, the Ubound function is used to determine the upper bound of the array. Ubound has a complementary function called Lbound, which returns the lower bound of an array. Also, the Preserve keyword is used inside the loop when redimming. This tells VB to keep all the data that is currently in the array. Also, I would like to bring up one more item regarding dynamic arrays. If you have a multi-dimensional dynamic array, you may only redim the last element of the array if you wish to preserve the data. In the following example, for instance, the last statement is illegal; you will get an array out of bounds error:
Code:
Dim myArray() As Integer ReDim myArray(5, 25) ' Ok ReDim myArray(6, 30) ' Ok ReDim Preserve myArray(7, 35) ' NOT Ok
If you really need to create a totally dynamic array, I won’t get into the mechanics of how to do so here – this is, after all a basic tutorial, but, you could create a dynamic array of dynamic arrays… Hmmm.

There are several functions that work closely with arrays. The first is called Array. This is somewhat confusing, but you must admit that it is easy to remember! You pass an argument list to Array; it returns a variant, holding an array with your arguments in the array elements.
Code:
Dim A as variant A = Array("Tom", "Dick", "Harry")
creates a three element variant array & places it into variant A.

Another commonly used function is the Split function. Split is used to break apart a string on delimiting characters, and place the discrete strings into a dynamic array. Consider the following:
Code:
Dim strWords() as string Dim strSentence as string StrSentence = "Jack and Jill went up the hill" StrWords = Split(strSentence, " ")
In this example, strWords(0) would contain "Jack", strWords(1) would contain "and", strWords(2) would contain "Jill", and so on. The delimiter could be any character, or any string of characters. The comma is a common delimiter, used in comma separated variable data files.

Well, that’s about it for a beginning discussion of Arrays. One of my Dad’s favorite sayings was "Don’t put all your eggs in one basket." But, with VB, it can be a LOT easier if you do put all your eggs… er, data, into one array.
__________________
Lou
"I have my standards. They may be low, but I have them!" ~ Bette Middler
"It's a book about a Spanish guy called Manual. You should read it." ~ Dilbert
"To understand recursion, you must first understand recursion." ~ unknown

Last edited by Squirm; 03-29-2003 at 01:17 PM.
Reply With Quote