Discovering Arrays

Tuesday Nov 19th 2002 by Karl Moore
Share:

Annoyed with arrays? Muddled by multi-dimensions? In this tutorial, Karl Moore finds out exactly what these 'hyped-up lists' are all about, discovers a host of new buzzwords along the way, plus talks about practical uses in the real world. An interesting read for any Visual Basic programmer.

The very first time I encountered arrays, I have to admit I was confused.

And who wouldn't be in a subject that includes buzzwords such as elements, multi-dimensions, population, dynamics, fixed-sizes and explicit boundaries? Oh boy.

But arrays really aren't all that horrid. They're just a hyped-up a way of temporarily storing a load of information sort of a regular variable that holds lots of different bits of data.

If you're unsure what a variable is, check out my Beginning Visual Basic tutorial here.

If you care to join me, your host Karl Moore, in this article, we'll be:

  • Figuring out what arrays are all about
  • Discovering how to use them within your apps
  • Checking out fixed-size and dynamic arrays
  • Covering a few neat tips and tricks
  • Getting all multi-dimensional

And all that without an ounce of geeky recondite language. Well, maybe just a little oh, come on, how would we nerds live without it? J

Top Tip: Why don't you print out this tutorial by clicking the print link to your right? This will allow you to work through the activities offline with greater ease.

First off, exactly what is an array? The Word thesaurus provides a few definitions; collection, selection and group. Oh, and dress.

Uhuh, spot the odd one out.

Those first three keywords probably best describe an array; it's a collection of information. A regular variable holds just one bit of information, such as a network username. An array however can hold many different bits of information, such as all your network usernames.

And that can be jolly useful. Let's say you need access the countries you ship to many times during your application. Wouldn't it be nice to throw all that information into one place and access it from wherever you wanted, without constantly dipping into a database?

That 'one place' can be an array.

Or perhaps you're creating a data entry application and want to take all the data from your user, temporarily storing it in a 'holding spot'. Then, at a set point, you may want to shove it all inside your database.

That 'holding spot' can be an array.

A friend of mine needed to take figures from a database and perform complex calculations on them within his Visual Basic application.

He threw the numbers into an array and started work.

I was once involved in a project where I needed to split a document up into separate paragraphs. Each paragraph needed analysing, words chopping and changing, lengths altering and so on.

Where did I store all that information? A dozen different variables one for each paragraph? Nope after all, what if there were more than a dozen paragraphs to analyse? Do I create a hundred different variables, just in case?

Nope, that wouldn't work it would use way too much memory and hey, what if I needed to analyse more than one hundred paragraphs?

Instead, I opted to store each paragraph individually within one single array. Simple.

So in brief, arrays are a groovy, tech-savvy way of storing many bits of information under one variable name.

This tutorial will show you how to use arrays; it presents the raw techniques and leaves you with thoughts on how you can make them work for you.

But be warned, this guide isn't full of ready-to-go, copy-and-paste code. Arrays just don't work like that. This tutorial merely gives ideas and techniques then leaves 'em with you to put to your full advantage.

Top Tip: This tutorial has also been created to complement future guides to three-tier architecture. So read on and swot up early!

And don't forget our usual VB-World guarantee; if you start using arrays and they don't dramatically improve your next application, we'll send you a hundred bucks*.

* Conditions apply. Offers ends yesterday.

In this section, we're going to have our first fumbling frolic with arrays.

We'll be creating an array, putting information into it, then displaying certain data in message boxes. On the next page, we'll continue expanding this project with talk of loops and two important array keywords, LBound and UBound.

  • Launch Visual Basic

First off, we're going to create our array and fill it with information.

  • Click View, Code to enter the code window behind Form1
  • Enter the following in the General Declarations section:
Dim MyArray(4) As String

This is your array. As you can see, there's not much difference between a regular string variable and a supercool array except the bracketed number. That number simply dictates how many items of information the array should hold.

  • Add a Command Button to your Form
  • Change it's Caption property to: Fill the Array
  • Insert the following code behind the button:
Private Sub Command1_Click()    ' Populate (fill) the array    MyArray(0) = "Karl"    MyArray(1) = "Ipy"    MyArray(2) = "Katrina"    MyArray(3) = "Mark"    MyArray(4) = "Jill"    End Sub

Do you understand what we've done so far? First off, we declared the array, passing it the number four. This tells the array it can hold up to five different pieces of information.

<Reader: Five? FIVE!?>

Yup, five. You see, in the wonderful world of arrays, counting is zero-based. That means you start at zero and work upwards. So if we declared a variable with the number three, it would have room for four pieces of information.

<Reader: Oh, I understand - you can have one if you want two. But can I have just one if I want to? And what if I want two but can't have one?>

<Ed: Hey, stop being difficult...>

<Karl: Mr Editor, please stop harassing my reader!>

<Ed: And you can zip it too, Karl. So where are ya working tomorrow?>

<Karl gets worried, puts on a serious face and suddenly attempts to change the subject>

Erm, yes, that code behind your Command Button erm, it simply inserts information into those array slots. In slot zero, we threw my name. Slot one saw my curiously christened friend, Ipy. Slot two, Katrina. And so on.

You wouldn't always throw information into arrays exactly like this however. Typically, you'd be retrieving values from a database or something equally as tech-savvy.

Well, that's all well and good, but at the moment you're simply taking my word that this array lark even works. Not that I shouldn't be trusted, but I must admit those thick eyebrows and crossed eyes do add a certain shadiness to my character.

But even if you run the project right now, unfortunately you'll not get any visible results all that array stuff is non-visual, it's like changing a variable in code. So let's add a little more code to test our hard work.

  • Add another Command Button to your Form
  • Change it's Caption property to: Get Stuff from Array
  • Throw the following code behind the button:
Private Sub Command2_Click()    On Error GoTo ArrayErr        Dim intArrayNo As Integer        intArrayNo = InputBox("Enter an array number to return:", _        "Choose a Number", 0)        MsgBox MyArray(intArrayNo)    Exit Sub    ArrayErr:    If Err.Number = 9 Then        MsgBox ("No such item in the array!")    Else        MsgBox Err.Description    End IfEnd Sub

It looks a little difficult, but this code simply grabs a number from the user and displays the corresponding item or 'element' from the array.

Well, that's the first bit of our application up-and-running. Go ahead and test it:

  • Press F5 to run your application
  • Try clicking on both your Command Buttons

Does it work? What happens when you enter a number outside our array range of zero to four? How about if you click our second command button before the first?

Now, there are two very important functions that go hand in hand with arrays.

They're called LBound and UBound.

Remember that our array holds five bits of information? Well, the LBound (lower boundary) function returns the lowest numbered item in the array. In our case, this is zero though it can change, and we'll see that later.

And unsurprisingly, the UBound (upper boundary) function returns exactly the opposite the highest numbered item in the array. For us, that's four.

Those figures 0 and 4 are known as the dimensions of our array. Try mentioning that word as often as possible. It sounds awfully impressive and might win you a date with a geekess sometime.

Now those dimensions (See? You're impressed, right?) are pretty useful for finding out how many pieces of data you have in the array, then cycling through them all to do a little processing of some sort.

Let's add a little code now to see these functions in action.

  • Add yet another Command Button to your Form
  • Change it's Caption property to: Cycle Through Array
  • Insert the following code behind the button:
Private Sub Command3_Click()    For i = LBound(MyArray) To UBound(MyArray)            MsgBox MyArray(i)        Next iEnd Sub

This code simply cycles through a loop from zero to four and displays a message box for the individual array items.

Top Tip: If you're unsure about loops, get the lowdown here (link to Beg VB Tut, loop section).

The good thing about this is that it's flexible. After all, we could change our array to hold six pieces of info, and this same piece of code would continue to work and display the correct number of message boxes.

But who wants to display message boxes all day? Certainly not you. Instead, you'll probably replace the message box bit with a little code to add the individual array items (elements) to a combo box. Or maybe a database. Or whatever.

Whew! Excellent, I'm glad you're keeping abreast with everything so far. Next up, I'm diving straight for third base, with a talk about these thingies called dynamic arrays, which are certainly a lot more exciting. But first, let's summarise the last couple of pages. We've learnt:

  • Arrays are created like this: codeDim MyArrayName(number) as DataType
  • By default, arrays are zero-based
  • If you try to access a non-existent array element, error nine steps in
  • You can use LBound and UBound to retrieve the dimensions of an array

You can download a sample of the small project we've just built here.

So far, we've created what is known as a fixed-sized array. That means when we declared the array, we said it would hold five different pieces of information no more, no less.

Of course, in the real world, that's probably a lil' bit impractical.

Let's say you've created the world's greatest sales package. Along with each purchase, the user has to select a sales person from the list.

Now, being the exceptionally brainy developer you are, you've decided to throw all the sales people into an array. No, not literally that could be painful. But you've put their names into an array.

And why not? After all, there are only two-dozen sales chaps and that data is accessed pretty frequently. Instead of constantly dipping into the main database and wasting precious resources, heck, why not just save that information in an array?

However on Monday, you're setting on a new employee, the sexy Swede, Iarma Noying. With the previous fixed-array way of working, you'd have to recompile and redistribute your entire program so your array can hold that one extra person.

But dynamic arrays can change size (dimension) as and when you want them to.

Note: The next few pages work on building a larger project. If you choose to follow the instructions, be sure to label your Command Buttons for clarity otherwise, it'll get mighty confusing. Alternatively, download the project here.

Let's check them out:

  • Create a new project in Visual Basic
  • Insert the following in the General Declarations section behind Form1:
Dim FavouriteThings() As Variant

Hey, you've just declared a dynamic array! It doesn't currently hold anything, but we'll soon change that.

  • Add a Command Button to your Form
  • Change it's Caption property to: Redimension the Array
  • Slot the following code behind your button:
Private Sub Command1_Click()    ReDim FavouriteThings(1 To 5)End Sub

Now this harmless piece of code determines the dimensions of our array one to five. We could have just done it like this:

ReDim FavouriteThings(4)

... but that means we have to use that horrid zero-based counting system. And I don't like that.

This way, we've determined that our FavouriteThings array should hold five different pieces of information, numbered one to five.

Top Tip: If you run ReDim on an array, it clears any existing information within that array unless you include the Preserve keyword, discussed later.

What's so special about redimensioning? Well, you could perhaps find out how many employees you have in your database and then redimension the array appropriately.

So you could, say, dip into your database, open a recordset containing the employees, count how many you have, then 'redimension' the array (ReDim) as we did. After that, you'd simply need to cycle round each record and add it to your array.

But we're not working with databases here, so I'm going to skip all that stuff still, at least you know it's possible. Let's continue.

Top Tip: If you're having problems in working with databases and arrays, post your questions on the Bulletin Board at www.vbforums.com

  • Add another Command Button to your Form
  • Change it's Caption property to: Populate (Fill) the Array
  • Insert the following code behind the button:
Private Sub Command2_Click()    FavouriteThings(1) = "Chocolate"    FavouriteThings(2) = "Summer Breeze"    FavouriteThings(3) = "Lavender"    FavouriteThings(4) = 3    FavouriteThings(5) = 9    End Sub

Here, we're throwing a little information into our array. I'm adding a few of my favourite things from chocolate to the number three.

Another Top Tip: It's worth noting that my FavouriteThings array was declared as a Variant, meaning it can hold many different types of data for example, the string 'Chocolate' as well as the integer 3. However, remember that I-Can-Hold-Anything Variants always take up much more memory than specific Data Types, such as String or Integer so always try to use the type that best suits your needs.

Yet Another Top Tip: One friend of mine needed to analyse statistics from a database. So he threw the numbers into an array and performed all the complex calculations within his Visual Basic application. So it just goes to show that arrays don't limit you to strings you can use them with virtually any data type!

Just One More Jolly Important Top Tip: In addition to declaring your arrays as Strings and Integers, etc you can also use them with custom data types, UDTs. These are particularly helpful if you want to store more than one chunk of information in an array for instance, say you wanted to store both a list of CustomerNames, plus CustomerID numbers in one array. You can do this by (a) defining your own data type (lookup User Defined Types or UDTs in the Visual Basic Help), then (b) declaring your array as that user defined type.

If you like, you can go ahead and test this dynamic array right now. Perhaps you could add a button that displays a particular element. Alternatively, if you're 'au faire' with everything so far, just cross your fingers and continue with the tutorial. It's your call.

Next up, we're going to try and put information into the sixth 'element' of our array. Yes, the sixth non-existent element remember, we only dimensioned our array to hold items one to five. Erm, not six.

As the song goes, 'There May Be Trouble Ahead':

  • Add yet another Command Button to your Form
  • Change it's Caption property to: Put Data into Sixth Element
  • Insert the following code behind the button:
Private Sub Command3_Click()On Error GoTo FavThingsErrFavouriteThings(6) = _InputBox("What do you want to put into the sixth, " & _"non-existent element of the array?", _"Question", "Boxer Dogs")Exit Sub    FavThingsErr:    MsgBox Err.Description    End Sub

This simply takes whatever you enter into the InputBox and attempts to throw it into the sixth element of your FavouriteThings array. But of course, the array doesn't have six elements.

  • Try running the application and clicking on all three command buttons

If you click them out of order, you should receive a few interesting errors. In fact if you click them in order, you should receive a few interesting errors. Coo, life sure is unfair.

So you got a 'Subscript Out Of Range' error, eh? Hey, just a wild guess.

We're now going to make room for that sixth element, in code.

Now we already know we can do this, as so:

ReDim FavouriteThings(1 To 6)

But this would clear everything current in the array, including summer breeze and the number nine. And I don't want that.

So instead we can use the Preserve keyword to ensure everything in the array is kept in the array.

  • Add another bloomin' Command Button to your Form
  • Change it's Caption property to: Make Room for Sixth Element

Top Tip: If you ain't labelling these button blighters, the project will soon become awfully messy. You really are labelling them, right? If not, you might want to work from the project download here.

  • Insert the following code behind your Command Button:
Private Sub Command4_Click()    ReDim Preserve FavouriteThings(1 To 6)End Sub

This tells Visual Basic to redimension the array to hold elements one to six, whilst preserving anything currently within it.

  • Run your application and click buttons one, two and three

These buttons (1) redimension your array to hold five elements, (2) put data into the array, (3) attempt to put information into the non-existent sixth element of the array.

  • Now hit the fourth button

This redimensions the array to make room for a sixth element, whilst still preserving its other information.

  • Now try to put information into the sixth element again, by clicking that third button once more

Ahah! Does it work now? If you don't receive an error, you've just altered the sixth element of your array. Wahoo!

But hold on just one lil' minute. We did that preserve thing to ensure all the information in the array stayed put. How do we know it's still there? By testing:

  • Add another (yes, another) Command Button to your Form
  • Change it's Caption property to: Display an Element
  • Throw the following code behind the button:
Private Sub Command5_Click()On Error GoTo PickOneErrDim intNumber As IntegerintNumber = InputBox("Which element do you wish to display?", _"Pick a Number", 4)MsgBox FavouriteThings(intNumber)    Exit SubPickOneErr:MsgBox Err.Description    End Sub

This simply accepts a number and displays the appropriate element of your array.

Try displaying the sixth element of an array before you redimension it with the fourth button. Then throw information into the sixth element with the third button.

Now use this last button to display the various elements of the array. Notice how after you redimension the array using the Preserve keyword all the array values are saved?

But try clicking that first button once more which redimensions the array to hold elements one to five, yet doesn't include the preserve keyword. Then display any of the elements using that last button once more. Notice how there isn't any information in any element? In other words, nothing has been preserved.

That's all whizzy and wonderful but how does this relate to real life programming, I hear you ask?

Well, let's say I have a user entering customer names on my form. Instead of adding them all to the database individually, I want to store them then do one mass update.

So I might decide to store all the customer names in an array then throw into a database later on.

Now, every time the user wants to enter a new customer, my program will typically redimension the array to hold one extra slot of information. Naturally, I wouldn't want to lose all the previously entered customer names, so that's where the Preserve keyword comes in handy.

So, you typically use the Preserve keyword when you want to resize (redimension) an array, whilst keeping anything currently within it.

Once more, let's briefly review what we've learnt over the past couple of pages:

  • You can declare dynamic arrays like this: Dim MyArray() as DataType
  • To alter the dimensions of an array, use: ReDim MyArray(x To y)
  • To alter the dimensions of an array whilst preserving any information currently within it, use: ReDim Preserve MyArray(x To y)

Before we move onto the next section, let's quickly add one more feature to our project. This one allows you to edit any individual item in the array. If the element you try to edit doesn't exist, it offers to redimension the array for you.

It's the longest piece of code we've written so far. Do you understand how it works?

  • Add another Command Button to your Form
  • Change it's Caption property to: Edit an Element (you are labelling these, right?)
  • Insert the following code behind the button:
Private Sub Command6_Click()On Error GoTo EditErrDim intArrayNumber As IntegerintArrayNumber = InputBox("Which array element " & _"would you like to change?", "Pick a Number")FavouriteThings(intArrayNumber) = _InputBox("What is the new value of element " & intArrayNumber, _"Enter Something", FavouriteThings(intArrayNumber))Exit Sub    EditErr:If Err.Number = 9 ThenIf MsgBox("Element number " & intArrayNumber & _" not present in the array. " & _"Would you like me to resize the array to hold elements 1 to " & _intArrayNumber & "?", vbYesNo + vbQuestion) = vbYes ThenReDim Preserve FavouriteThings(1 To intArrayNumber)End IfElseMsgBox Err.DescriptionEnd If    End Sub

One lovely keyword in the world of arrays is Erase. Or as I prefer to call it, Zap.

Zapping your array means, literally, killing it. Haha - Asta la Vista, Array!

I mean, don't get me wrong; it still exists. But it has no bally dimensions, no data, no anything. It's a void chasm of nothingness.

<Ed: How poetic!>

  • Add another Command Button to your Form
  • Change it's Caption property to: Erase Array

Getting used to this yet?

  • Insert the following line of code behind the button:
Private Sub Command7_Click()Erase FavouriteThingsEnd Sub

Try running your application. Redimension the array, put something into that sixth element, mess around here and there. Then zap it.

Now try editing the fourth element or some such. You'll get an 'Error 9 - Subscript Out Of Range' error. That's because you zapped your array, causing it to die and shrivel up into a tiny ball of steel no larger than a frog's wedding tackle.

Haha! The power of the Zapster!!

So you see, this keyword is great when you just want to forget everything you've done so far and start again. Jolly useful.

Top Tip: The Erase keyword completely zaps all dimensions of dynamic variables. But fixed-sized variables, as discussed in the first few pages of this tutorial always keep their initial dimensions and can't be changed in code.

To complete our mini project here, I'd like you to add one more chunk of code. This is a feature that will display the dimensions of your array.

  • Add another... yep.
  • Change it's Caption property to: Show Dimensions
  • Insert the following code behind the button:
Private Sub Command8_Click()On Error GoTo BoundErrCall MsgBox("Here are the dimensions of your array:" & _vbNewLine & "LBound: " & LBound(FavouriteThings) & _vbNewLine & "UBound: " & UBound(FavouriteThings), vbInformation)Exit SubBoundErr:If Err.Number = 9 ThenCall MsgBox("Your array has no dimensions. " & _        "It may have just been zapped!", vbExclamation)ElseMsgBox Err.DescriptionEnd IfEnd Sub

This simply displays the LBound and UBound properties of your array. If the array doesn't have an LBound or UBound (ie, you've ZAPPED IT!) then error nine occurs and our lil' message box is displayed.

Well, that's all for this mini project. Don't forget you can download the full source code here.

So, key points we've learned in this section:

  • You can use Erase to wipe clean a dynamic array
  • LBound and UBound cause an error nine if no dimensions exist

If you fancy becoming an array wizard, there are a couple of other little tips and tricks you might be interested in.

Array Function

The Array function can turn a regular variant variable into an array. Let's peek at an example:

Dim MyVariable As VariantMyVariable = Array("These", "Are", "Elements", _                   "Of", "My", "Array")For i = LBound(MyVariable) To UBound(MyVariable)MsgBox MyVariable(i)Next i

Try running this example. The code takes a variant variable and turns it into an array. It's just a cunningly quick way to create an array.

IsArray Function

So, if regular variables can be turned into arrays how do you know whether something is an array or isn't? Oh boy.

Thankfully the IsArray function can help out. Just call IsArray, passing the possible array. It will return a True or False value.

Here's a little sample code:

Dim RegularArray(1 To 5) As StringDim DynamicArray() As StringDim ToBeChangedVariable As VariantDim RegularVariable As VariantToBeChangedVariable = Array(1, 2, 3)MsgBox ("RegularArray - " & IsArray(RegularArray))MsgBox ("DynamicArray - " & IsArray(DynamicArray))MsgBox ("ToBeChangedVariable - " & IsArray(ToBeChangedVariable))MsgBox ("RegularVariable - " & IsArray(RegularVariable))

IsArray returns True for both RegularArray and DynamicArray. After we use the Array function on ToBeChangedVariable, it turns into an array meaning IsArray returns True there also.

But the final RegularVariable check returns a False. That isn't an array.

IsZapped Function

OK, so there isn't an intrinsic Visual Basic function called IsZapped. It's my own creation and can be incredibly useful.

Instead of adding error handling to your code just in case an array has been 'zapped' and left dimensionless, why not just use this groovy little IsZapped function.

If everything is A-OK, it returns a False it ain't zapped. If the array has no dimensions, it returns a True.

Here's the code:

Public Function IsZapped(ArrayIn As Variant) As BooleanOn Error GoTo DimensionErrDim i As Integeri = LBound(ArrayIn)IsZapped = FalseExit Function    DimensionErr:    If Err.Number = 9 ThenIsZapped = TrueElseMsgBox Err.DescriptionEnd If    End Function

There are two extra Visual Basic functions you might find amazingly useful; Split and Join.

  • Split Takes a string, such as 'This is my sentence' and splits it up into individual array elements, depending on a 'delimiter'. In this case, the delimiter could be a space (" "), meaning we get an array of four elements containing This, Is, My, Sentence.
  • Join This does the opposite of Split. It takes data from an array and shoves it all together into one long string, with an optional delimiter (which separates the bits of information from each other). So, if we used this on the array created above with a space delimiter (" "), it would take This, Is, My, Sentence and throw them all together, adding spaces in between. In other words, we get back our original sentence 'This is my sentence'.

These concepts always seem exceptionally weird when explained like this - so let's conclude this section with a geek peek at some sample code:

Private Sub Command1_Click()Dim strFirstText As StringDim strSecondText As StringDim StringArray() As StringstrFirstText = "This is my sentence"' First, the splitStringArray = Split(strFirstText, " ")For i = LBound(StringArray) To UBound(StringArray)MsgBox StringArray(i)Next i' And now the joinstrSecondText = Join(StringArray, " ")MsgBox strSecondText    End Sub

So far, we've talked about arrays with one single dimension. In essence, they're just a hyped-up list of values.

We can change the number of elements in such arrays, alter the values of individual items, even zap it all.

However there's something else you can do with 'em... add new dimensions.

Now, if I didn't loathe Star Wars so, you'd probably be the victim of a few futuristic dimension-related Garlick jokes right now. Or is it Dahlick? And how do you spell it? I forget.

Still, 'multiple dimensions' sounds terribly futuristic and scientific so I'm definitely up for it. Anything for a new buzzword.

Top Tip: This section is optional and included for completeness you see, erm, it's kinda unlikely you'll actually ever use the techniques demonstrated. So if you're in a hurry, feel free to skip the rest of this page!

Now, let's imagine we've declared our array like this:

Dim NDArray(1 To 5)

In visual terms, our array looks something like this:

NDArray(1)
NDArray(2)
NDArray(3)
NDArray(4)
NDArray(5)

We can also add another dimension to our arrays, by declaring them as such: Dim NDArray(1 To 5, 1 To 5)

In visual terms, our two-dimensional array ends up looking something like this a block of twenty-five individual elements:

NDArray(1,1)NDArray(1,2)NDArray(1,3)NDArray(1,4)NDArray(1,5)
NDArray(2,1)NDArray(2,2)NDArray(2,3)NDArray(2,4)NDArray(2,5)
NDArray(3,1)NDArray(3,2)NDArray(3,3)NDArray(3,4)NDArray(3,5)
NDArray(4,1)NDArray(4,2)NDArray(4,3)NDArray(4,4)NDArray(4,5)
NDArray(5,1)NDArray(5,2)NDArray(5,3)NDArray(5,4)NDArray(5,5)

So if we wanted to insert a value into the very first 'cell', we would use something like: NDArray(1,1)= "Test"

And to insert into the last cell: NDArray(5,5)= "Test"

You can even expand arrays out into three dimensions - though it's a little more difficult to draw. You do it in much the same way as before, and can imagine it rather like one big block containing many tiny little blocks, like those cubes you used to play with in math class: NDArray(1 To 5, 1 To 5, 1 To 5)


Blow Up!

Incidentally, that's where three-dimensional (3D) gets its name from. Most television screens are two-dimensional, meaning you see just height and width. But with 3D films or images you get to see height, width and depth, as in this (rather poorly drawn) visual representation of our three-dimensional array.

You can even expand arrays out into four and five dimensions measured in scientific terms of time and space, I think but they're awfully difficult to draw.

But to be completely honest, unless you really need such whopping great arrays for mathematical purposes or for creating some kind of highly complex, custom-built, multi-dimensional data warehousing type-application, you really don't need to dive past a simple one-dimensional array.

You'll find arrays of two-dimensions pretty rare, and chances of coming across a three-dimensional array are about the same as spotting the entire cast of Lion King merrily dancing to the tune of Hi Lili Hi Lo in the Highlands of Bonny Scotland.

Still, just to prove it can be done, let's create a sample two-dimensional array project.

  • Create a new Standard EXE
  • Declare the following dynamic array in General Declarations:
Dim NDArray() As Integer

Now, we're going to tell Visual Basic to redimension this array to hold two dimensions, one containing elements one to five, the second also containing elements one to five. In other words, we're going to create ourselves a virtual 2D grid similar to the one I drew above.

  • Add a Command Button (Caption: Redim 2D Array), then insert the following code behind it:
Private Sub Command1_Click()ReDim NDArray(1 To 5, 1 To 5)End Sub

In this sample project, I'm going to create a multiplication table. The code may seem a bit strange at first, but once you see it all up and running, you'll understand what's happening.

  • Add another Command button (Caption: Fill 2D Array), throwing the following code behind it:
Private Sub Command2_Click()    For i = 1 To 5            For y = 1 To 5                    NDArray(i, y) = i * y        Next y        Next iEnd Sub

This just loops around i five times. Within each loop of i, a sub loop goes around y five times also. The value of i * y is then inserted into the (i, y) location of NDArray.

Seems weird, don't it? Try running the code in your own head first. Go through it all line by line. What results do you get? Do you see how it works? If not, don't worry it'll become clear later.

Next up, we're going to add another form with a grid, on which we will plot the data from our array.

Let's go:

  • Add another Form to your project

Now let's add a reference to the Microsoft FlexGrid control:

  • Click Project, Components
  • Scroll down, tick 'Microsoft FlexGrid Control', then click OK

Now:

  • Draw out the MSFlexGrid control onto your new Form
  • Change the following properties of your MSFlexGrid, observing how the grid alters as you do so:

Rows - 5

Cols - 5

FixedRows - 0

FixedCols - 0

Great! We've just prepared the second form to display the contents of our two-dimensional array, which in its simplest form, is a five-by-five grid.

  • Add another Command Button (Caption: Fill Grid) to your first Form

Now, in the code we're going to use to put data into that grid, I'll be using the LBound and UBound functions to determine the lower and upper boundaries of the array, a lot like we did before.

However, remember that LBound returns the first element of an array, whilst UBound returns the last? Well, that was with a simple one-dimensional array. Now we're working with two dimensions!

So it's worth noting that both LBound and UBound have one extra optional argument. After passing the array to the function, you can add a number to indicate which dimension you're referring to. If no number is entered, the first dimension is assumed.

That means LBound(NDArray, 1) returns the lowest element number of the first dimension in our case, one. And UBound(NDArray, 2) returns the highest element number of the second dimension in our case, five.

It's a small detail, but definitely worth highlighting.

Note: For more information about this, lookup LBound or UBound in Visual Basic help.

  • Insert this code behind the button:
Private Sub Command3_Click()    Form2.Show        For i = LBound(NDArray, 1) To UBound(NDArray, 1)    ' Translates into: For i = 1 to 5            For y = LBound(NDArray, 2) To UBound(NDArray, 2)        ' Translates into: For y = 1 to 5                            Form2.MSFlexGrid1.TextMatrix(i - 1, y - 1) = NDArray(i, y)                ' Throws the (i, y) array value into the grid                Next y        Next i    End Sub

This code simply cycles round the array and dumps the information into our grid.

Top Tip: The TextMatrix bit specifies where in the grid the information should be placed. If you're wondering why we take one from i and y to specify the location of the grid cell you want to use... well, it would seem the grid uses that horrid zero-based counting system too so the first cell is (0,0), not (1,1). That's why we need to minus one from our array, which uses a one-based counting system. Sheesh! <Karl shivers>

And the resulting form should look something like this:

There we have it: our multiplication table!

If I wanted to know four times five, I simply need to look down the number five column, then look across the number four row and see where they cross over. That's where the answer will lie.

Not terribly useful, but a cool party trick if ever I saw one...

Briefly, let's review the important points in this section:

  • Arrays can have multiple dimensions, though it isn't very common
  • To retrieve the LBound and UBound of certain dimensions within an array, use this format: LBound(ArrayName, DimensionNumber)

Top Tip: If you're going to be working with multi-dimensional arrays and want to use the Preserve command too, be sure to check out the Visual Basic help file first, as special rules apply!

< Ed: You can download the code for this project here. >

In this standalone tutorial, we explored the wonderful world of arrays.

We discovered exactly what arrays are and how we can use them to improve our applications, plus checked out a few array hints and tips to make our lives easier. Along the way, we created numerous projects to demonstrate the encountered techniques.

We concluded the tutorial with a peek into the multi-dimensional advanced array arena, plus created our own multiplication table in code. And, if you've been listening carefully, you will have also picked up a handful of new buzzwords pure ammo for the non-violent geek.

In conclusion, arrays can be jolly useful things. Let's say you're displaying products for sale. Instead of constantly dipping inside backend databases, wouldn't it be helpful to store product names, prices and descriptions in a regularly-refreshed local array?

It certainly would and that's just the beginning. With arrays and the techniques you've learned today, you can really start to make their power work for you. Make sure you use 'em in your next application.

Well, that's about all for this tutorial. I hope this information will help you in your programming career and don't forget... carry on zapping! J

Until next time, this is Karl Moore wishing you all a good night tonight. Goodnight!

Share:
Home
Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved