Working with Arrays of Variables


Working with Arrays of Variables

In this section, you'll learn about arrays, a useful method for storing almost any amount of data during program execution. Arrays are a powerful and time-tested mechanism for storing logically related values in a program. The developers of BASIC, Pascal, C, and other popular programming languages incorporated arrays into the earliest versions of these products to refer to a group of values by using one name and to process those values individually or collectively.

Arrays can help you track a small set of values in ways that are impractical using traditional variables. For example, imagine creating a nine-inning baseball scoreboard in a program. To save and recall the scores for each inning of the game, you might be tempted to create two groups of nine variables (a total of 18 variables) in the program. You'd probably name them something like Inning1HomeTeam, Inning1VisitingTeam, and so on, to keep them straight. Working with these variables individually would take considerable time and space in your program. Fortunately, with Visual Basic you can organize groups of similar variables into an array that has one common name and an easy-to-use index. For example, you can create a two-dimensional (2-by-9) array named Scoreboard to contain the scores for the baseball game. Let's see how this works.

Creating an Array

You create, or declare, arrays in program code just as you declare simple variables. As usual, the place in which you declare the array determines where it can be used, or its scope, as follows:

  • If an array is declared locally in a procedure, it can be used only in that procedure.

  • If an array is declared at the top of a form, it can be used throughout the form.

  • If an array is declared publicly in a module, it can be used anywhere in the project.

When you declare an array, you typically include the information shown in the following table in your declaration statement.

Information in an array declaration statement

Description

Array name

The name you'll use to represent your array in the program. In general, array names follow the same rules as variable names. (See Chapter 5, “Visual Basic Variables and Formulas, and the .NET Framework,” for more information about variables.)

Data type

The type of data you'll store in the array. In most cases, all the variables in an array are the same type. You can specify one of the fundamental data types, or if you're not yet sure which type of data will be stored in the array or whether you'll store more than one type, you can specify the Object type.

Number of dimensions

The number of dimensions your array will contain. Most arrays are one-dimensional (a list of values) or two-dimensional (a table of values), but you can specify additional dimensions if you're working with a complex mathematical model, such as a three-dimensional shape.

Number of elements

The number of elements your array will contain. The elements in your array correspond directly to the array index. In Visual Basic 2005, the first array index is always 0 (zero).

TIP
Arrays that contain a set number of elements are called fixed-size arrays. Arrays that contain a variable number of elements (arrays that can expand during the execution of the program) are called dynamic arrays.

Declaring a Fixed-Size Array

The basic syntax for a public fixed-size array is

Dim ArrayName(Dim1Index, Dim2Index, ...) As DataType

The following arguments are important:

  • Dim is the keyword that declares the array. Use Public instead if you place the array in a module.

  • ArrayName is the variable name of the array.

  • Dim1Index is the upper bound of the first dimension of the array, which is the number of elements minus 1.

  • Dim2Index is the upper bound of the second dimension of the array, which is the number of elements minus 1. (Additional dimensions can be included if they're separated by commas.)

  • DataType is a keyword corresponding to the type of data that will be included in the array.

For example, to declare a one-dimensional string array named Employees that has room for 10 employee names (numbered 0 through 9), you can type the following in an event procedure:

Dim Employees(9) As String

In a module, the same array declaration looks like this:

Public Employees(9) As String

Using new syntax supported by Visual Basic 2005 (but not Microsoft Visual Basic .NET 2002 or 2003), you can also explicitly specify the zero lower bound of the array with the following code in an event procedure:

Dim Employees(0 To 9) As String

This “0 to 9” syntax is included to make your code more readable—newcomers to your program will understand immediately that the Employees array has 10 elements numbered 0 through 9. However, the lower bound of the array must always be zero. You cannot use this syntax to create a different lower bound for the array.

Setting Aside Memory

When you create an array, Visual Basic sets aside room for it in memory. The following illustration shows conceptually how the 10-element Employees array is organized. The elements are numbered 0 through 9 rather than 1 through 10 because array indexes always start with 0. (Again, the Option Base statement in Visual Basic 6, which allows you to index arrays beginning with the number 1, is no longer supported.)

graphic

To declare a public two-dimensional array named Scoreboard that has room for two rows and nine columns of Short integer data, you can type this statement in an event procedure or at the top of the form:

Dim Scoreboard(1, 8) As Short

Using the new Visual Basic 2005 syntax that emphasizes the lower (zero) bound, you can also declare the array as follows:

Dim Scoreboard(0 To 1, 0 To 8) As Short

After you declare such a two-dimensional array and Visual Basic sets aside room for it in memory, you can use the array in your program as if it were a table of values, as shown in the following illustration. (In this case, the array elements are numbered 0 through 1 and 0 through 8.)

graphic

Working with Array Elements

To refer to an element of an array, you use the array name and an array index enclosed in parentheses. The index must be an integer or an expression that results in an integer. For example, the index could be a number such as 5, an integer variable such as num, or an expression such as “num-1”. (The counter variable of a For…Next loop is often used.) For example, the following statement assigns the value “Leslie” to the element with an index of 5 in the Employees array example in the previous section:

Employees(5) = "Leslie"

This statement produces the following result in our Employees array:

graphic

Similarly, the following statement assigns the number 4 to row 0, column 2 (the top of the third inning) in the Scoreboard array example in the previous section:

Scoreboard(0, 2) = 4

This statement produces the following result in our Scoreboard array:

graphic

You can use these indexing techniques to assign or retrieve any array element.

Creating a Fixed-Size Array to Hold Temperatures

The following exercise uses a one-dimensional array named Temperatures to record the daily high temperatures for a seven-day week. The program demonstrates how you can use an array to store and process a group of related values on a form. The Temperatures array variable is declared at the top of the form, and then temperatures are assigned to the array by using an InputBox function and a For…Next loop, which you learned about in Chapter 7, “Using Loops and Timers.” The loop counter is used to reference each element in the array. The array contents are then displayed on the form by using a For…Next loop and a text box object. The average high temperature is also calculated and displayed.

The LBound and UBound Functions

To simplify working with the array, the Fixed Array program uses the UBound function to check for the upper bound, or top index value, of the array. UBound is an earlier Visual Basic keyword that's still quite useful. With it you can process arrays without referring to the declaration statements that defined exactly how many values the array would hold. The closely related LBound function, which confirms the lower bound of an array, is still valid in Visual Basic, but because all Visual Basic arrays now have a lower bound of zero (0), the function simply returns a value of 0. The UBound and LBound functions have the syntax

LBound(ArrayName) UBound(ArrayName)

where ArrayName is the name of an array that's been declared in the project.

Use a fixed-size array

  1. Start Microsoft Visual Studio, and create a new Visual Basic Windows Application project named My Fixed Array.

  2. Draw a text box object on the form.

  3. Set the Multiline property of the TextBox1 object to True so that you can resize the object.

  4. Resize the text box object so that it fills up most of the form.

  5. Draw two wide button objects on the form below the text box object, oriented one beside the other.

  6. Set the following properties for the form and its objects:

    Object

    Property

    Setting

    TextBox1

    ScrollBars

    Vertical

    Button1

    Text

    “Enter Temps”

    Button2

    Text

    “Display Temps”

    Form1

    Text

    “Fixed Array Temps”

    Your form looks like the one shown below.

    graphic

  7. In Solution Explorer, click the View Code button to display the Code Editor.

  8. Scroll to the top of the form's program code, and directly below the Public Class Form1 statement, type the following array declaration:

    Dim Temperatures(0 To 6) As Single

    This statement creates an array named Temperatures (of the type Single) that contains seven elements numbered 0 through 6. Because the array has been declared at the top of the form, it is available in all the event procedures in the form.

  9. Display the form again, and then double-click the Enter Temps button (Button1).

    The Button1_Click event procedure appears in the Code Editor.

  10. Type the following program statements to prompt the user for temperatures and to load the input into the array:

    Dim Prompt, Title As String Dim i As Short Prompt = "Enter the day's high temperature." For i = 0 To UBound(Temperatures)     Title = "Day " & (i + 1)     Temperatures(i) = InputBox(Prompt, Title) Next

    The For…Next loop uses the short integer counter variable i as an array index to load temperatures into array elements 0 through 6. Rather than using the simplified For loop syntax

    For i = 0 to 6

    to process the array, I chose a slightly more complex syntax involving the UBound function for future flexibility. The For loop construction

    For i = 0 To UBound(Temperatures)

    determines the upper bound of the array by using the UBound statement. This technique is more flexible because if the array is expanded or reduced later, the For loop automatically adjusts itself to the new array size.

    To fill the array with temperatures, the event procedure uses an InputBox function, which displays the current day by using the For loop counter.

  11. Display the form again, and then double-click the Display Temps button (Button2).

  12. Type the following statements in the Button2_Click event procedure:

    Dim Result As String Dim i As Short Dim Total As Single = 0 Result = "High temperatures for the week:" & vbCrLf & vbCrLf For i = 0 To UBound(Temperatures)     Result = Result & "Day " & (i + 1) & vbTab & _       Temperatures(i) & vbCrLf     Total = Total + Temperatures(i) Next Result = Result & vbCrLf & _   "Average temperature:  " & Format(Total / 7, "0.0") TextBox1.Text = Result

    This event procedure uses a For…Next loop to cycle through the elements in the array, and it adds each element in the array to a string variable named Result, which is declared at the top of the event procedure. I've used several literal strings, constants, and string concatenation operators (&) to pad and format the string by using carriage returns (vbCrLf), tab characters (vbTab), and headings. The vbCrLf constant, used here for the first time, contains the carriage return and linefeed characters and is an efficient way to create new lines. The vbTab constant is also used here for the first time to put some distance between the day and temperature values in the Result string. At the end of the event procedure, an average for the temperatures is determined, and the final string is assigned to the Text property of the text box object, as shown in this statement:

    TextBox1.Text = Result

  13. Click the Save All button on the Standard toolbar to save the project. Specify the c:\vb05sbs\chap11 folder as the location.

    Now you'll run the program.

    TIP
    The complete Fixed Array program is located in the c:\vb05sbs\chap11\fixed array folder.

  14. Click the Start Debugging button on the Standard toolbar to run the program.

  15. Click the Enter Temps button, and when prompted by the InputBox function, enter seven different temperatures. (How about using the temperatures from your last vacation?)

    The InputBox function dialog box looks like this:

    graphic

  16. After you've entered the temperatures, click the Display Temps button.

    Using the array, Visual Basic displays each of the temperatures in the text box and prints an average at the bottom. Your screen looks similar to this:

    graphic

  17. Click the Close button on the form to end the program.

Creating a Dynamic Array

As you can see, arrays are quite handy for working with lists of numbers, especially if you process them by using For…Next loops. But what if you're not sure how much array space you'll need before you run your program? For example, what if you want to let the user choose how many temperatures are entered into the Fixed Array program?

Visual Basic handles this problem efficiently with a special elastic container called a dynamic array. Dynamic arrays are dimensioned at run time, either when the user specifies the size of the array or when logic you add to the program determines an array size based on specific conditions. Dimensioning a dynamic array takes several steps because although the size of the array isn't specified until the program is running, you need to make “reservations” for the array at design time. To create a dynamic array, you follow these basic steps:

  • Specify the name and type of the array in the program at design time, omitting the number of elements in the array. For example, to create a dynamic array named Temperatures, you type

    Dim Temperatures() As Single

  • Add code to determine the number of elements that should be in the array at run time. You can prompt the user by using an InputBox function or a text box object, or you can calculate the storage needs of the program by using properties or other logic. For example, the following statements get the array size from the user and assign it to the Days variable of type Short:

    Dim Days As Short Days = InputBox("How many days?", "Create Array")

  • Use the variable in a ReDim statement to dimension the array, subtracting 1 because arrays are zero-based. For example, the following statement sets the size of the Temperatures array at run time by using the Days variable:

    ReDim Temperatures(Days - 1)

    IMPORTANT
    With ReDim, you should not try to change the number of dimensions in an array that you've previously declared.

  • Use the UBound function to determine the upper bound in a For…Next loop, and process the array elements as necessary, as shown here:

    For i = 0 to UBound(Temperatures)     Temperatures(i) = InputBox(Prompt, Title) Next

In the following exercise, you'll use these steps to revise the Fixed Array program so that it can process any number of temperatures by using a dynamic array.

Use a dynamic array to hold temperatures

  1. Open the Code Editor to display the program code for the Fixed Array project.

  2. Scroll to the top of the form's code, in which you originally declared the Temperatures fixed array.

  3. Remove 0 To 6 from the Temperatures array declaration so that the array is now a dynamic array.

    The statement looks like the following:

    Dim Temperatures() As Single

  4. Add the following variable declaration just below the Temperatures array declaration:

    Dim Days As Integer

    The integer variable Days will be used to receive input from the user and to dimension the dynamic array at run time.

  5. Scroll down in the Code Editor to display the Button1_Click event procedure, and modify the code so that it looks like the following. (The changed or added elements appear in bold italic.)

    Dim Prompt, Title As String Dim i As Short Prompt = "Enter the day's high temperature." Days = InputBox("How many days?", "Create Array") If Days > 0 Then ReDim Temperatures(Days - 1) For i = 0 To UBound(Temperatures)     Title = "Day " & (i + 1)     Temperatures(i) = InputBox(Prompt, Title) Next

    The fourth and fifth lines prompt the user for the number of temperatures he or she wants to save, and then the user's input is used to dimension a dynamic array. The If…Then decision structure is used to verify that the number of days is greater than 0. (Dimensioning an array with a number less than 0 or equal to zero generates an error.) Because index 0 of the array is used to store the temperature for the first day, the Days variable is decremented by 1 when dimensioning the array. The Days variable isn't needed to determine the upper bound of the For…Next loop—as in the previous example, the UBound function is used instead.

  6. Scroll down in the Code Editor to display the Button2_Click event procedure. Modify the code so that it looks like the following routine. (The changed elements appear in bold italic.)

    Dim Result As String Dim i As Short Dim Total As Single = 0 Result = "High temperatures:" & vbCrLf & vbCrLf For i = 0 To UBound(Temperatures)     Result = Result & "Day " & (i + 1) & vbTab & _       Temperatures(i) & vbCrLf     Total = Total + Temperatures(i) Next Result = Result & vbCrLf & _   "Average temperature:  " & Format(Total / , "0.0") TextBox1.Text = Result

    The Days variable replaces the number 7 in the average temperature calculation at the bottom of the event procedure. I also edited the “High temperatures” heading that will be displayed in the text box.

  7. Change the Form1.Text property to Dynamic Array.

  8. Save your changes to disk.

    TIP
    On the companion CD-ROM, I gave this project a separate name to keep it distinct from the Fixed Array project. The complete Dynamic Array project is located in the c:\vb05sbs\chap11\dynamic array folder.

  9. Click the Start Debugging button to run the program.

  10. Click the Enter Temps button.

  11. Type 5 when you're prompted for the number of days you want to record, and then click OK.

  12. Enter five temperatures when prompted.

  13. When you've finished entering temperatures, click the Display Temps button.

    The program displays the five temperatures on the form along with their average. Your screen looks similar to this:

    graphic

  14. Click the Close button on the form to end the program.

You've practiced using the two most common array types in Visual Basic programming. When you write your own programs, you'll soon use much larger arrays, but the concepts are the same, and you'll be amazed at how fast Visual Basic can complete array-related computations.



Microsoft Visual Basic 2005 Step by Step
Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))
ISBN: B003E7EV06
EAN: N/A
Year: 2003
Pages: 168

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net