19.12.2012 Views

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Houston 3.7 $31,488 67 8<br />

Los Angeles 14.5 $36,711 59 8<br />

New York 18.1 $38,445 73 11<br />

Philadelphia 5.9 $35,797 70 8<br />

San Francisco 6.3 $41,459 60 11<br />

Washington 3.9 $47,254 32 17<br />

Note: Column 4 gives the percentage of residents who were born in their current state of residence. Column<br />

5 gives the percentage of residents age 25 or older with a graduate or professional degree.<br />

Source: The 1990 Census<br />

SOLUTION:<br />

Data are read from a file into parallel arrays by the Form_Load event procedure. When cmdDisplayStats<br />

is clicked, the collection of parallel arrays is sorted based on the array pop( ). Each time two items are<br />

interchanged in the array pop( ), the corresponding items are interchanged in each of the other arrays. This<br />

way, for each city, the items of information remain linked by a common subscript.<br />

Dim city(1 To 10) As String, pop(1 To 10) As Single, income(1 To 10) As Single<br />

Dim natives(1 To 10) As Single, advDeg(1 To 10) As Single<br />

Private Sub cmdDisplayStats_Click()<br />

Call SortData<br />

Call ShowData<br />

End Sub<br />

Private Sub Form_Load()<br />

Dim i As Integer<br />

‘Assume the data for city name, population, medium income, % native,<br />

‘<strong>and</strong> % advanced degree have been placed in the file “CITYSTAT.TXT”<br />

‘(First line of file is “Boston”, 4.2, 40666, 73, 12)<br />

Open “CITYSTAT.TXT” For Input As #1<br />

For i = 1 To 10<br />

Input #1, city(i), pop(i), income(i), natives(i), advDeg(i)<br />

Next i<br />

Close #1<br />

End Sub<br />

Private Sub ShowData()<br />

Dim i As Integer<br />

‘Display ordered table<br />

picTable.Cls<br />

picTable.Print , “Pop. in”, “Med. income”, “% Native”, “% Advanced”<br />

picTable.Print “Metro Area”, “millions”, “per hsd”, “to State”, “Degree”<br />

picTable.Print For i = 1 To 10<br />

picTable.Print city(i); Tab(16); pop(i), income(i), natives(i), advDeg(i)<br />

Next i<br />

End Sub<br />

Private Sub SortData()<br />

Dim passNum As Integer, index As Integer<br />

‘Bubble sort table in descending order by population<br />

For passNum = 1 To 9<br />

For index = 1 To 10 - passNum<br />

If pop(index) < pop(index + 1) Then Call<br />

SwapData(index)<br />

End If<br />

Next index<br />

Next passNum<br />

End Sub<br />

Sorting <strong>and</strong> Searching 187

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!