|
Free
computer Tutorials
|
![]() |
home |
Stay
at Home and Learn
|
||||||
What is an Array? |
|||||||
|
In this section, you are going to learn all about the power of arrays, and how easy they can make your programming life. First, you need to know what an array is.
What is an array?So far you've been using variables quite a lot. You've put numbers into variables, and you've put text into variables. But you've only done this one at a time: you've put one number into a variable, or one string of text. You've been doing this: Dim MyNumber As Integer MyNumber = 5 Or this Dim MyText As String MyText = "A String is really just text" Or even this: Dim MyNumber As Integer = 5 So one variable was holding one piece of information. An array is a variable that can hold more than one piece of information at a time. The MyNumber variable above held one number 5. If you had an array variable called MyNumbers - plural - you could hold more than one number at a time. You set them up like this: Dim MyNumbers(4) As Integer MyNumbers(0)
= 1 When you set up an array with the Dim word, you put the name of your array variable, and tell Visual Basic how many items you want to store in the array. But you need to use parentheses around your figure. You then assign your data to a position in the array. In the example above we've set up an Integer array with 5 items in it. We've then said put number 1 into array position 0, put number 2 into array position 1, put number 3 into array position 2, and so on. You might be thinking that the array was set to the number 4 - MyNumbers(4) - but always remember that an array starts counting at zero, and the first position in your array will be zero. So that's what an array is - a variable that can hold more than one piece of data at a time -but how do they work? A programming example might help to clear things up.
Dim MyNumbers(4) As Integer MyNumbers(0) =
1 MsgBox("First
Number is: " & MyNumbers(0)) Test out the programme when you are finished. The numbers 10 to 50 should have been displayed in your message boxes. In the code, we first set up an Integer array with 5 items in it. Dim MyNumbers(4) As Integer We then assigned values to each position in the array. MyNumbers(0) = 1 To get at the values in the array, and display them in messages boxes, we just used the array name, followed by the position in the array. MsgBox("First Number is: " & MyNumbers(0))
Add another messages box statement on a line below the others. Put this: MsgBox("Sixth Number is: " & MyNumbers(5)) Run your programme again, and click the Button. What happened? To explain what went wrong, and why, click the next part below.
Move on to the Next part of the Arrays tutorial --> |