Section 7.3. Some Additional Types of Arrays


[Page 341]

7.3. Some Additional Types of Arrays

So far, the array elements have been standard data types. This section considers arrays of controls and arrays of a new compound data type designed by the programmer.

Control Arrays

We have seen many examples of the usefulness of subscripted variables. They are essential for writing concise solutions to many programming problems. Because of the utility that subscripts provide, Visual Basic also provides for arrays of labels, text boxes, and buttons. Since labels, text boxes, and buttons are referred to generically in Visual Basic as controls, arrays of these objects (or of any other control) are called control arrays. Note:Since Visual Basic does not provide for arrays of masked text boxes, we will only use ordinary text boxes for input.

Control arrays are created in much the same way as any other array; that is, with a statement of the form

Dim arrayName(n) As ControlType


or

Dim arrayName() As ControlType


For instance, the following statements declare control arrays.

Dim lblTitle(10) As Label Dim txtNumber(8) As TextBox Dim btnAmount() As Button


Example 1.
(This item is displayed on pages 341 - 342 in the print version)

A department store has five departments. The following program requests the amount of sales for each department and displays the total sales for the store. The five labels identifying the departments are grouped into an array of labels and the five text boxes for the individual amounts are grouped into an array of text boxes. The initial settings for these labels are specified at run time in the frmSales_Load event procedure instead of being specified at design time. The Text properties of the labels are set to be "Department 1", "Department 2", and so on.

Object

Property

Setting

frmSales

Text

Daily Sales:

Label1Label5 TextBox1TextBox5 btnCompute

Text

Compute Total Sales

lblTotal

Text

Total Sales

txtTotal

ReadOnly

True



[Page 342]

Dim lblDept(4) As Label DimtxtDept(4)As TextBox Private Sub frmSales_Load(...) Handles MyBase. Load   lblDept(0) = Label1   lblDept(1) = Label2   lblDept(2) = Label3   lblDept(3) = Label4   lblDept(4) = Label5   txtDept(0) = TextBox1   txtDept(1) = TextBox2   txtDept(2) = TextBox3   txtDept(3) = TextBox4   txtDept(4) = TextBox5   'Set the labels' Text property to the corresponding department   'Set the text boxes' Text property to the empty string   For depNum As Integer = 1 To 5     lblDept(depNum - 1).Text = "Department " & depNum & ":"   Next End Sub Private Sub btnCompute_Click(...) Handles btnCompute.Click   Dim totalSales As Double = 0   For depNum As Integer = 1 To 5     totalSales += CDbl(txtDept(depNum - 1).Text)  Next  txtTotal.Text = FormatCurrency(totalSales) End Sub


[Run, enter amounts into the text boxes, and then click the button.]


[Page 343]

Structures

Some of the data types we have worked with so far are Double, Integer, String, and Boolean. A structure provides a convenient way of packaging as a single unit several related variables of different types. In previous versions of Visual Basic a structure was called a user-defined type (UDT).

Three pieces of related information about colleges are "name," "state," and "year founded." A structure type capable of holding this data is defined by the following block of statements located in the Declarations section of the Code window.

Structure College   Dim name As String   Dim state As String   Dim yearFounded As Integer End Structure


Each of the three subvariables of the structure type is called a member. A structure variable of the type College is declared by a statement such as

Dim college1 As College


Each member is accessed by giving the name of the structure variable and the member, separated by a period. For instance, the three members of the structure variable college1 are accessed as college1.name, college1.state, and college1.yearFounded.

In general, a structure type is defined by a Structure block of the form

Structure StructureType  Dim memberName1 As MemberType1  Dim membername2 As MemberType2  .  .  . End Structure


where StructureType is the name of the user-defined data type; memberName1, memberName2,..., are the names of the members of the structure; and MemberType1, MemberType2,..., are the corresponding member types, such as String, Integer, Double, or Boolean.

A structure variable, structureVar, is declared to be of the user-defined type by a statement of the form

Dim structureVar As StructureType



[Page 344]

Example 2.
(This item is displayed on pages 344 - 345 in the print version)

The following program stores information about two colleges into structure variables of type College and uses the variables to determine which college is older. Note: In the third line of the btnOlder_Click event procedure, all the member values of college1 are assigned simultaneously to collegeOlder.

Object

Property

Setting

frmFirst

Text

Find Earlier College

btnFirst

Text

Get Data on First College

btnSecond

Text

Get Data on Second College

btnOlder

Text

Display Data on Older College

txtResult

ReadOnly

True


Structure College   Dim name As String   Dim state As String   Dim yearFounded As Integer End Structure Dim college1, college2, collegeOlder As College Private Sub btnFirst_Click(...) Handles btnFirst.Click   Dim prompt As String   college1.name = InputBox("Enter name of first college.", "Name")   college1.state = InputBox("Enter state of first college.", "State")   prompt = "Enter the year the first college was founded."   college1.yearFounded = CInt(InputBox(prompt, "Year")) End Sub Private Sub btnSecond_Click(...) Handles btnSecond.Click   Dim prompt As String   college2.name = InputBox("Enter name of second college.", "Name")   college2.state = InputBox("Enter state of second college.", "State")   prompt = "Enter the year the second college was founded."   college2.yearFounded = CInt(InputBox(prompt, "Year")) End Sub Private Sub btnOlder_Click(...) Handles btnOlder.Click   If (college1.yearFounded < college2.yearFounded) Then     collegeOlder = college1   Else     collegeOlder = college2   End If   txtResult.Text = collegeOlder.name & " was founded in " & _           collegeOlder.state & " in " & collegeOlder.yearFounded & "." End Sub



[Page 345]

[Run, click the first button, and respond to the input boxes with Princeton University, New Jersey, 1746. Click the second button; respond to the input boxes with Yale University, Connecticut, 1701. Finally, click the third button.]

Example 3.
(This item is displayed on pages 345 - 346 in the print version)

The file COLLEGES.TXT holds the name, state, and year founded for each of the 27 colleges in the United States founded before 1800. The first three lines of the file contain the data Harvard University, MA, 1636. The following program places the information about the colleges into an array of structures. The array is then used to display the names of the colleges in a specified state. Note: The masked text box has Mask "LL".

Structure College   Dim nameAs String   Dim state As String   Dim yearFounded As Integer End Structure Dim school(26) As College Private Sub frmColleges_Load(...) HandlesMyBase.Load   'Place the data for each college into the array school()   Dim i As Integer = - 1   Dim sr As IO.StreamReader = IO.File.OpenText("COLLEGES.TXT")   Do While (sr.Peek <> - 1)     i += 1     school(i).name = sr.ReadLine 
[Page 346]
school(i).state = sr.ReadLine school(i).yearFounded = CInt(sr.ReadLine) Loop sr.Close() End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display the colleges in COLLEGES.TXT located in the given state lstCollege.Items.Clear() For i As Integer = 0 To 26 If (school(i).state = mtxtState.Text) Then lstCollege.Items.Add(school(i).name, & " " & _ school(i).yearFounded) End If Next End Sub


[Run, type the name of a state into the masked text box, and click the button.]

So far, the members of structures have had elementary types; such as String or Integer. However, the type for a member can be another structure or an array type. When a member is given an array type, the defining Dim statement must not specify the upper bound; this task must be left to a ReDim statement. Example 4 demonstrates the use of both of these nonelementary types of members. In addition, the example shows how to pass a structure variable to a Sub procedure.

Example 4.
(This item is displayed on pages 346 - 347 in the print version)

The following program totals a person's college credits and determines whether they have enough credits for graduation. Notes: The structure variable person is local to the btnGet_Click event procedure. In the fourth line of the procedure, person.name.firstName should be thought of as (person.name).firstName.

Object

Property

Setting

frmStatus

Text

Gaduation Status

btnGet

Text

Get Data and Determine Status

txtResult

ReadOnly

True



[Page 347]

Structure FullName   Dim firstName As String   Dim lastName As String End Structure Structure Student   Dim name As FullName   Dim credits() As Integer End Structure Private Sub btnGet_Click(...) Handles btnGet.Click   Dim numYears As Integer   Dim person As Student   txtResult.Clear()   person.name.firstName = InputBox("First Name:")   person.name.lastName = InputBox("Second Name:")   numYears = CInt(InputBox("Number of years completed:"))   ReDim person.credits(numYears  1)   For i As Integer = 0 To numYears  1     person.credits(i) = CInt(InputBox("Credits in year " & i + 1))   Next   DetermineStatus(person) End Sub Sub DetermineStatus(ByVal person As Student)   Dim total As Integer = 0   For i As Integer = 0 To person.credits.GetUpperBound(0)      total += person.credits(i)   Next   If (total >= 120) Then     txtResult.Text = person.name.firstName & " " & _              person.name.lastName & " has enough credits to graduate."   Else     txtResult.Text = person.name.firstName & " " & _                      person.name.lastName & " needs " & _                      (120 - total) & " more credits to graduate."   End If End Sub


[Run, click the button, and respond to requests for input with Miranda, Smith, 3, 34, 33, 34.]


[Page 348]
Comments

  1. Structures are similar to arrays in that they both store and access data items using a common name. However, the elements in an array must be of the same data type, whereas the members in a structure can be a mixture of different data types. Also, the different elements of an array are identified by their indices, whereas the members of a structure are identified by a name following a period.

  2. Statements of the form

    lstBox.Items.Add(structureVar)

    where structureVar is a structure variable, do not perform as intended. Each member of a structure should appear separately in a lstBox.Items.Add statement. Also, comparisons involving structures using the relational operators <, >, =, <>, <=, and >= are valid only with individual members of the structure, not with the structures themselves.

Practice Problems 7.3

1.

Find the errors in the following event procedure

Sub btnDisplay_Click(...) Handles btnDisplay.Click   Structure Team     Dim school As String     Dim mascot As String   End Structure   Team.school = "Rice"   Team.mascot = "Owls"   txtOutput.Text = Team.school & " " & Team.mascot End Sub


2.

Correct the code in Practice Problem 1.

Exercises 7.3

In Exercises 1 through 4, use the following form (already filled in by the user) to determine the output displayed in the read-only text box at the bottom of the form when the button is clicked. The rectangular group of text boxes on the form consist of four arrays of text boxestxtWinter(), txtSpring(), txtSummer(), and txtFall()with each array having indexes ranging from 0 to 3.


[Page 349]

1.

Private Sub btnProcess_Click(...) Handles btnProcess.Click   Dim total As Double = 0   For itemNum As Integer = 0 To 3     total += CDbl(txtWinter(itemNum).Text)   Next   txtBox.Text = "Expenses for winter: " & FormatCurrency(total) End Sub


2.

Private Sub btnProcess_Click(...) Handles btnProcess.Click   Dim total As Double = 0   total += CDbl(txtWinter(2).Text)   total += CDbl(txtSpring(2).Text)   total += CDbl(txtSummer(2).Text)   total += CDbl(txtFall(2).Text)   txtBox.Text = "Annual water bill: " & FormatCurrency(total) End Sub


3.

Private Sub btnProcess_Click(...) Handles btnProcess.Click   Dim diff As Double   Dim total As Double = 0   For i As Integer = 0 To 3     diff = CDbl(txtSummer(i).Text) - CDbl(txWinter(i).Text)     total += diff   Next   txtBox.Text = "Summer bills top winter bills by " & _                FormatCurrency(total) End Sub


4.

Private Sub btnProcess_Click(...) Handles btnProcess.Click   Dim total As Double = 0   For itemNum As Integer = 0 To 3     total += TotalCateg(itemNum)   Next   txtBox.Text = "Total major expenses: " & FormatCurrency(total) End Sub 
[Page 350]
Function TotalCateg(ByVal itemNum As Integer) As Double Dim total As Double = 0 total += CDbl(txtWinter(itemNum).Text) total += CDbl(txtSpring(itemNum).Text) total += CDbl(txtSummer(itemNum).Text) total += CDbl(txtFall(itemNum).Text) Return total End Function


In Exercises 5 through 8, determine the output displayed when the button is clicked.

5.

Structure Appearance   Dim height As Double   Dim weight As Double End Structure Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim person1, person2 As Appearance   person1.height = 72   person1.weight = 170   person2.height = 12 * 6   If person1.height = person2.height Then    lstOutput.Items.Add("heights are same")   End If   person2 = person1   lstOutput.Items.Add(person2.weight) End Sub


6.

Structure TestData   Dim name As String   Dim score As Double End Structure Dim sr As IO.StreamReader = IO.File.OpenText("SCORES.TXT") Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim student As TestData   For i As Integer = 1 to 3     GetScore(student)     DisplayScore(student)   Next   sr.Close() End Sub Sub GetScore(ByRef student As TestData)   student.name = sr.ReadLine   student.score = CDbl(sr.ReadLine) End Sub Sub DisplayScore(ByVal student As testData)   lstOutput.Items.Add(student.name & " " & student.score) End Sub


(Assume that the six lines of the file SCORES.TXT contain the following data:Joe, 18, Moe, 20, Roe, 25.)


[Page 351]
7.

Structure Address   Dim street As String   Dim city As String   Dim state As String End Structure Structure Citizen   Dim name As String   Dim residence As Address End Structure Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim person As Citizen   person.name = "Mr. President"   person.residence.street = "1600 Pennsylvania Avenue"   person.residence.city = "Washington"   person.residence.state = "DC"   txtOutput.Text = person.name & " lives in " & _             person.residence.city & ", " & person.residence.state End Sub


8.

Structure TaxData   Dim socSecNum As String   Dim numExem As Integer 'Number of exemptions   Dim maritalStat As String   Dim hourlyWage As Double End Structure Structure Employee   Dim name As String   Dim hrsWorked As Double   Dim taxInfo as TaxData End Structure Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim worker as Employee   worker.name = "Hannah Jones"   worker.hrsWorked = 40   worker.taxInfo.hourlyWage = 20   txtOutput.Text = worker.name " & earned " & _     FormatCurrency(worker.hrsWorked * worker.taxInfo.hourlyWage) End Sub


In Exercises 9 through 11, determine the errors.

9.

Structure Nobel   Dim peace as String   Dim year as Integer End Structure Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim prize As Nobel   peace = "International Atomic Energy Agency" 
[Page 352]
year = 2005
txtBox.Text = peace & " won the " & year & " Nobel Peace Prize." End Sub


10.

Structure Vitamins    Dim a As Double    Dim b As Double End Structure Private Sub btnDisplay_Click(...) Handles btnDisplay.Click    Dim minimum As Vitamins    minimum.b = 200    minimum.a = 500    lstOutput.Items.Add(minimum) End Sub


11.

Structure BallGame    Dim hits As Double    Dim runs As Double End Structure Private Sub btnDisplay_Click(...) Handles btnDisplay.Click    Dim game1, game2 As BallGame    game1.hits = 15    game1.runs = 8    game2.hits = 17    game2.runs = 10    If game1 > game2 Then      txtOutput.Text = "The first game was better."    Else      txtOutput.Text = "The second game was at least as good."    End If End Sub


12.

Write a line or lines of code as instructed in Steps (a) through (e) to fill in the missing lines in the following program.

Structure Appearance   Dim height As Double 'Inches   Dim weight As Double 'Pounds End Structure Structure Person   Dim name As String   Dim stats As Appearance End Structure Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim person1, person2 As Person   (missing lines) End Sub



    [Page 353]
  1. Give person1 the name Michael.

  2. Set Michael's height and weight to 71 and 190, respectively.

  3. Give person2 the name Jacob.

  4. Set Jacob's height and weight to 70 and 175, respectively.

  5. If one person is both taller and heavier than the other, display a sentence of the form "[name of bigger person] is bigger than [name of smaller person]."

A campus club has 10 members. The following program stores information about the students into an array of structures. Each structure contains the student's name and a list of the courses he or she is currently taking. Exercises 13 through 16 request that an additional event procedure be written for this program.

Structure Student   Dim name As String   Dim courses() As String End Structure Dim club(9) As Student Private Sub frmStudents_Load(...) Handles MyBase.Load   Dim pupil As student   'Enter data for first student   pupil.name = "Juan Santana"   ReDim pupil.courses(2)   pupil.courses(0) = "CMSC 100"   pupil.courses(1) = "PHIL 200"   pupil.courses(2) = "ENGL 120"   club(0) = pupil   'Enter data for second student   pupil.name = "Mary Carlson"   ReDim pupil.courses(3)   pupil.courses(0) = "BIOL 110"   pupil.courses(1) = "PHIL 200"   pupil.courses(2) = "CMSC 100"   pupil.courses(3) = "MATH 220"   club(1) = pupil   'Enter names and courses for remaining 8 people in the club End Sub


13.

Write the code for a btnDisplay_Click event procedure that will display the names of all the students in the club in a list box.

14.

Write the code for a btnDisplay_Click event procedure that will display the names of all the students in the club who are registered for three courses.

15.

Write the code for a btnDisplay_Click event procedure that will display the names of all the students in the club who are enrolled in CMSC 100.

16.

Write the code for a btnDisplay_Click event procedure that will display the names of all the students in the club who are not enrolled in CMSC 100.


[Page 354]
17.

Write a program to compute a student's grade-point average for a semester. Allow for as many as six courses. For each course, the grades (A, B,...) should be entered in an element of an array of six text boxes, and the semester hours credits entered into another array of six text boxes. After the student fills in the grades and clicks on a button, a Function procedure should compute the GPA. Then a Sub procedure should display the GPA along with one of two messages. A student with a GPA of 3 or more should be informed that he or she has made the honor roll. Otherwise, the student should be congratulated on having completed the semester.

18.

Table 7.1 gives the U.S. Census Bureau projections for the populations (in millions) of the states predicted to be the most populous in the year 2025. Write a program that allows the user to enter the current populations of the states into an array of text boxes, computes the projected population growths for the states in an array of text boxes, and gives the percentage growth for the collection of five states. The growth is calculated with the formula

growth = (projected pop. current pop.)/current pop

Table 7.1. State populations in the year 2025.

State

Population in 2025

California

49.3

Txas

27.2

New York

19.8

Illinois

13.4

Florida

20.7


Percentage growth can be displayed as FormatPercent(growth). Test the program with the current populations shown in Figure 7.4

Figure 7.4. Sample run for Exercise 18.



[Page 355]
19.

Write a program to look up data on notable tall buildings. The program should declare a user-defined data type named "Building" with the members "name", "city", "height", and "stories". This interactive program should allow the user to type the name of a building into a text box and then search through an array of structures to determine the city, height, and number of stories of the building when a button is pressed. If the building is not in the array, then the program should so report. Place the information in Table 7.2 into a text file, and read it into the array.

Table 7.2. Tallest buildings.

Building

City

Height (ft)

Stories

Empire State

New York

1250

102

sars Tower

Chicago

1454

110

Texas Commerce Tower

Houston

1002

75

Transamerica Pyramid

San Francisco

853

48


20.

Given the following flight schedule, write a program to load this information into an array of structures, and ask the user to specify a flight number. Have the computer find the flight number and display the information corresponding to that flight. Account for the case where the user requests a nonexistent flight.

Flight #

Origin

Destination

Departure Time

117

Tucson

Dallas

8:45 a.m.

239

LA

Boston

10:15 a.m.

298

Albany

Reno

1:35 p.m.

326

Houston

New York

2:40 p.m.

445

New York

Tampa

4:20 p.m.


21.

Table 7.3 contains the names and number of stores of the top 10 pizza chains in 2003. Write a program to place these data into an array of structures, compute the total number of stores for these 10 chains, and display a table giving the name and percentage of total stores for each of the companies.

Table 7.3. Top 10 pizza chains as of July 1,2003 (and numbers of stores).

Name

Stores

Name

Stores

1. Pizza Hut

7,523

6. Papa Murphy's

750

2. Domino's

4,904

7. Godfather's

566

3. Little Caesar's

2,850

8. Round Table

485

4. Papa John's

2,574

9. CiCi's Pizza

465

5. Sbarro

790

10. Chuck E. Cheese's

460

Source: Pizza Marketing Quarterly, Summer 2003


22.

A retail store has five bins, numbered 1 to 5, each containing a different commodity. At the beginning of a particular day, each bin contains 45 items. Table 7.4 shows the cost per item for each of the bins and the quantity sold during that day.

Table 7.4. Costs of items and quantities sold for Exercise 22.
(This item is displayed on page 356 in the print version)

Bin

Cost per Item

Quantity Sold

1

3.00

10

2

12.25

30

3

37.45

9

4

7.49

42

5

24.95

17


Write a program to

  1. place the cost per item and the quantity sold from each bin into an array of structures;


  2. [Page 356]
  3. display a table giving the inventory at the end of the day and the amount of revenue obtained from each bin;

  4. compute the total revenue for the day;

  5. list the number of each bin that contains fewer than 20 items at the end of the day.

Solutions to Practice Problems 7.3

1.

The event procedure contains two errors. First, the definition of a structure cannot be inside a procedure; it must be typed into the Declarations section of the Code window. Second, the statements Team.school = "Rice" and Team.mascot = "Owls" are not valid. Team.school and Team.mascot are not valid. "Team" should be replaced by a variable of type Team that has previously been declared.

2.

   Structure Team     Dim school As String     Dim mascot As String   End Structure   Private Sub btnDisplay_Click(...) Handles btnDisplay.Click     Dim squad As Team     squad.school = "Rice"     squad.mascot = "Owls"     txtOutput.Text = squad.school & " "& squad.mascot   End Sub





An Introduction to Programming Using Visual Basic 2005
Introduction to Programming Using Visual Basic 2005, An (6th Edition)
ISBN: 0130306541
EAN: 2147483647
Year: 2006
Pages: 164

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