[Page 679 (continued)] Exercises 7.1 3. | Have a dessert spoon. | 5. | 9 4 | 7. | 11 | 9. | A rook is worth more than a bishop | 11. | Your total is 280. | 13. | The ReDim statement should not end with an "As String" clause. | 15. | When k > 5, the array subscript will be a negative number. | 17. | The number 2 in the second statement should be deleted. | 19. | river(0) river(1) river(2) river(3) river(4) Thames Ohio Amazon Volga Nile river(0) river(1) river(2) river(3) river(4) Ohio Amazon Volga Nile Thames | 21. | (a) 2 (b) 7 (c) 10 (d) 9 | | [Page 680] | 23. | Replace the btnDisplay_Click event with the following: Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display the numbers of the games won by the team in the text box. Dim foundFlag As Boolean = False lstGamesWon.Items.Clear() For i As Integer = 0 To upperBound If teamName(i) = txtName.Text Then lstGamesWon.Items.Add(i + 1) foundFlag = True End If Next If Not foundFlag Then lstGamesWon.Items.Add("Never won a Super Bowl.") End If End Sub | 25. | ReDim quantities(100) | 27. | Dim marx(3) As String 'In Declarations section of Code window Private Sub frmMarx_Load(...) Handles MyBase.Load marx(0) = "Chico" marx(1) = "Harpo" marx(2) = "Groucho" marx(3) = "Zeppo" End Sub | 29. | 'Store in b() the reverse of the values in a(). For i As Integer = 0 To 4 b(i) = a(4 - i) Next | 31. | 'Display the elements of the array a() in columns. Dim fmtStr As String = "{0,15}{1,15}{2,15}{3,15}{4,15}" For i As Integer = 0 To 25 Step 5 lstOutput.Items.Add(String.Format(fmtStr, a(i), a(i + 1), _ a(i + 2), a(i + 3), a(i + 4))) Next | 33. | 'Compare arrays a() and b() for same values. Dim differFlag As Boolean = False For i As Integer = 0 To 9 If a(i) <> b(i) Then differFlag = True End If Next If differFlag Then txtOutput.Text = "The arrays are not identical." Else txtOutput.Text = "The arrays have identical values." End If | 35. | 'Curve grades by adding 7. For i As Integer = 0 To 11 grades(i) += 7 Next | | [Page 681] | 37. | Private Sub btnScores_Click(...) Handles btnScores.Click 'Read data from a file, and display their frequencies. Dim frequency(4) As Integer 'Stores the results Dim num As Integer Dim fmtStr As String = "{0,-12} {1,-9:N0}" 'Open the data file for input. Dim sr As IO.StreamReader = IO.File.OpenText("SCORES.TXT") 'Loop over the 30 lines in the file. For i As Integer = 1 To 30 num = CInt(sr.ReadLine) 'Increment the frequency element that belongs to the number. 'Divide by 10, and get the integer part. frequency(CInt(Int(num / 10))) += 1 Next sr.Close() 'Always close the reader when finished with it. 'Display the results. lstOutput.Items.Add(String.Format(fmtStr, "Interval", "Frequency")) For i As Integer = 0 To 4 lstOutput.Items.Add(String.Format(fmtStr, _ CStr(i * 10) & " to " & CStr((i + 1) * 10 - 1), _ frequency(i))) Next End Sub | 39. | Dim pres(42) As String 'Holds the Presidents' names Private Sub frmPres_Load(...) Handles MyBase.Load 'Loads the data from the file into the array Dim sr As IO.StreamReader = IO.File.OpenText("USPRES.TXT") For i As Integer = 0 To 42 pres(i) = sr.ReadLine Next sr.Close() End Sub Private Sub btnDisplayFullNames_Click(...) _ Handles btnDisplayFullNames.Click 'Display the presidents who have the requested first name. Dim space As Integer Dim firstName As String Dim foundFlag As Boolean = False lstFullNames.Items.Clear() 'Loop over all presidents. For i As Integer = 0 To 42 'The first name is the string before the first space. space = pres(i).IndexOf(" ") firstName = pres(i).Substring(0, space) 'If the first name matches, then display the president. If firstName = txtFirstName.Text Then lstFullNames.Items.Add(pres(i)) foundFlag = True End If Next 'If not found, display message. If Not foundFlag Then lstFullNames.Items.Add("Name not found.") End If End Sub [Page 682]Private Sub lstDisplayPres_Click(...) Handles lstDisplayPres.Click 'Display the presidents between two numbers, inclusive. lstPres.Items.Clear() 'Loop from the lower number to the upper number. For i As Integer = CInt(txtLowerNum.Text) To CInt(txtUpperNum.Text) lstPres.Items.Add(i & ". " & pres(i - 1)) Next End Sub | 41. | Private Sub btnShow_Click(...) Handles btnShow.Click 'Test two phrases to see if they are anagrams. Dim first(25), second(25) As Integer 'Holds frequencies Dim letter As String Dim result As Boolean = True 'Convert both phrases to uppercase. txtFirst.Text = txtFirst.Text.ToUpper txtSecond.Text = txtSecond.Text.ToUpper 'Count the frequencies of the first phrase. For i As Integer = 0 To txtFirst.Text.Length - 1 letter = txtFirst.Text.Substring(i, 1) 'Increment the frequency element belonging to the letter. If (letter >= "A") And (letter <= "Z") Then first(Asc(letter) - Asc("A")) += 1 End If Next 'Count the frequencies of the second phrase. For i As Integer = 0 To txtSecond.Text.Length - 1 letter = txtSecond.Text.Substring(i, 1) 'Increment the frequency element belonging to the letter. If (letter >= "A") And (letter <= "Z") Then second(Asc(letter) - Asc("A")) += 1 End If Next 'Compare the two frequencies. For i As Integer = 0 To 25 'If the frequencies differ, set the result flag to False. If first(i) <> second(i) Then result = False End If Next 'Display the result. If result Then txtOutput.Text = "The two phrases are anagrams." Else txtOutput.Text = "The two phrases are not anagrams." End If End Sub | Exercises 7.2 3. | Michigan | 5. | less than greater than equals less than | | [Page 683] | 7. | total rainfall for first quarter: 10 inches | 9. | Change txtOutput.Text = city to txtOutput.Text = city(1). You can't display an entire array with one statement. | 11. | n is incremented by 1 even if the user enters a negative number to stop and see the product. Move the incrementing inside the If block just before the statement num(n) = number. | 13. | In the Sub procedure CopyArray, the parentheses should be removed in the line b() = a() | 15. | Sub Ascending() 'Determine if array is ascending. Dim i As Integer = 0 Dim orderFlag As Boolean = True Do While (i < scores.GetUpperBound(0)) And (orderFlag) If scores(i) > scores(i + 1) Then orderFlag = False End If i += 1 Loop If orderFlag Then txtOutput.Text = "Array is ascending." Else txtOutput.Text = "Array is not ascending." End If End Sub | 17. | Sub WhatOrder() 'Determine if order is ascending, descending, both, or neither. Dim ascFlag As Boolean = True Dim descFlag As Boolean = True Dim i as Integer = 0 Do While (i < scores.GetUpperBound(0)) And (ascFlag Or descFlag) If scores(i) > scores(i + 1) Then ascFlag = False End If If scores(i) < scores(i + 1) Then descFlag = False End If i += 1 Loop If ascendFlag And descendFlag Then txtOutput.Text = "Array is both ascending and descending." ElseIf (Not ascendFlag) And (Not descendFlag) Then txtOutput.Text = "Array is neither ascending nor descending." ElseIf ascendFlag Then txtOutput.Text = "Array is ascending." Else txtOutput.Text = "Array is descending." End If End Sub | 19. | Sub MergeOrderedWithDups() Dim indexA, indexB As Integer Dim doneA, doneB As Boolean 'Merge ascending arrays, with duplications. [Page 684] ReDim c(39) indexA = 0 indexB = 0 doneA = False doneB = False 'Loop over each element of the resulting array. For indexC As Integer = 0 To 39 'If a's element is less than b's, add a's to c. If ((a(indexA) <= b(indexB)) And Not doneA) Or (doneB) Then c(indexC) = a(indexA) 'Get next element from a. If indexA < 19 Then indexA = indexA + 1 Else doneA = True End If Else 'Otherwise, add b's element to c. c(indexC) = b(indexB) 'Get next element from b If indexB < 19 Then indexB = indexB + 1 Else doneB = True End If End If Next End Sub | 21. | Dim states(49) As String 'Holds state data Dim count As Integer 'Number of states stored Private Sub btnInsert_Click(...) Handles btnInsert.Click 'Insert a state into the array. Dim position As Integer 'If there is no more room in the array, display a message. If count >= 50 Then MsgBox("Fifty states have already been entered.", 0, _ "No more room.") Else 'Store the new state as the next element. states(count) = txtState.Text 'Find the place to insert the state. position = 0 Do While states(position) < txtState.Text position += 1 Loop 'If the position already holds the state, then display message. If (states(position) = txtState.Text) And (position < count) Then MsgBox("State already exists in the list.", 0, "Exists") Else 'Shift the states above the position. For i As Integer = count - 1 To position Step -1 states(i + 1) = states(i) Next [Page 685] 'Insert the new state in the position, and increment counter. states(position) = txtState.Text count += 1 End If 'Clear input and output, and reset focus for next input. lstOutput.Items.Clear() txtState.Clear() txtState.Focus() End If End Sub Private Sub btnDelete_Click(...) Handles btnDelete.Click 'Remove a state from the list. Dim position As Integer = 0 'Find the state within the array. Do While (position < count - 1) And (txtState.Text > states(position)) position += 1 Loop 'If the state is not found or no states stored, then display message. If (count = 0) Or (txtState.Text <> states(position)) Then MsgBox("The state is not in the list.", 0, "Not found") Else count = count - 1 'Decrement counter. 'Shift array above position down by one. For i As Integer = position To count - 1 states(i) = states(i + 1) Next lstOutput.Items.Clear() txtState.Clear() txtState.Focus() End If End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display the array in the list box. lstOutput.Items.Clear() For i As Integer = 0 To count - 1 lstOutput.Items.Add(states(i)) Next txtState.Clear() txtState.Focus() End Sub | 23. | Dim grades(99) As Integer 'Stores grade data Dim count As Integer 'Number of grades stored Private Sub btnRecord_Click(...) Handles btnRecord.Click 'Add a score to the array. 'If no more room, then display error message. If count >= 100 Then MsgBox("100 scores have been entered.", 0, "No more room.") Else 'Store the input into the array. grades(count) = CInt(txtScore.Text) count += 1 'Reset input. lstOutput.Items.Clear() [Page 686] txtScore.Clear() txtScore.Focus() End If End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display average of grades and the number above average. Dim avg As Double, aboveAvg As Integer avg = Average(grades, count) aboveAvg = AboveAverage(grades, count, avg) lstOutput.Items.Clear() lstOutput.Items.Add("The average is " & FormatNumber(avg, 2)".") lstOutput.Items.Add(FormatNumber(aboveAvg, 0) & _ " students scored above the average.") End Sub Function Average(ByVal scores() As Integer, ByVal cnt As Integer) _ As Double 'Calculate the average score. Dim sum As Double = 0 For i As Integer = 0 To cnt - 1 sum += scores(i) Next 'The average is the sum divided by the count; account for 0 count. If cnt = 0 Then Return 0 Else Return sum / cnt End If End Function Function AboveAverage(ByVal scores() As Integer, _ ByVal cnt As Integer, _ ByVal average As Double) As Integer 'Count the number of scores above the average score. Dim num As Integer = 0 For i As Integer = 0 To cnt - 1 If scores(i) > average Then num += 1 End If Next Return num End Function | 25. | Private Sub btnUpdate_Click(...) Handles btnUpdate.Click 'Merge two sets of data into a master set. Dim colors(71), retired(7), added(55) As String Dim i, j As Integer LoadArray(colors, "PRE1990COLORS.TXT") LoadArray(retired, "RETIREDCOLORS.TXT") LoadArray(added, "ADDEDCOLORS.TXT") 'Remove the retired colors from the array. ReDim Preserve colors(120) i = 0 j = 0 'Shift the array by the amount in j. Do While i <= 71 - 7 If colors(i) = retired(j) Then j += 1 End If [Page 687] colors(i) = colors(i + j) i += 1 Loop 'Insert the added colors into the master set. i = 0 j = 0 Do While j <= 55 If added(j) < colors(i) Then 'Insert new color. For k As Integer = 63 + j To i Step -1 colors(k + 1) = colors(k) 'Shift array. Next colors(i) = added(j) j += 1 End If lstOutput.Items.Add(colors(i)) i += 1 Loop 'Display the rest of the colors. For k As Integer = i To 119 lstOutput.Items.Add(colors(k)) Next End Sub Sub LoadArray(ByRef data() As String, ByVal fileName As String) 'Load string data from a file. Dim sr As IO.StreamReader = IO.File.OpenText(fileName) 'Fill the array, and close the reader. For i As Ineger = 0 To data.GetUpperBound(0) data(i) = sr.ReadLine() Next sr.Close() End Sub | Exercises 7.3 1. | Expenses for winter: $4,271.66 | 3. | Summer bills top winter bills by $67.09 | 5. | heights are same 170 | 7. | Mr. President lives in Washington, DC | 9. | peace should be prize.peace, and year should be prize.year. | 11. | The condition (game1 > game2) is not valid. Structures can only be compared one member at a time. | 13. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click lstOutput.Items.Clear() For i As Integer = 0 To club.GetUpperBound(0) lstOutput.Items.Add(club(i).name) Next End Sub | 15. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Displays the students who are enrolled in a course Dim subject As String = "CMSC 100" [Page 688] lstOutput.Items.Clear() 'Loop over all students in the club. For i As Integer = 0 To club.GetUpperBound(0) 'Loop over all courses for that student. For j As Integer = 0 To club(i).courses.GetUpperBound(0) 'If a course matches, display the student's name. If club(i).courses(j) = subject Then lstOutput.Items.Add(club(i).name) End If Next Next End Sub | 17. | Dim grades(5) As TextBox 'Refers to grade textboxes Dim hours(5) As TextBox 'Refers to hours textboxes Structure Course Dim grade As String 'Grade in the course Dim hours As Double 'Number of credit-hours End Structure Private Sub frmGrades_Load(...) Handles MyBase.Load 'Associate the textbox arrays with the textboxes grades(0) = txtGrade1 grades(1) = txtGrade2 grades(2) = txtGrade3 grades(3) = txtGrade4 grades(4) = txtGrade5 grades(5) = txtGrade6 hours(0) = txtHours1 hours(1) = txtHours2 hours(2) = txtHours3 hours(3) = txtHours4 hours(4) = txtHours5 hours(5) = txtHours6 End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Calculate and display the grade point average. Dim courses(5) As Course 'Holds the courses Dim numGrades As Integer 'Read the data into the courses array until there is no more data. numGrades = 0 For count As Integer = 0 To 5 If (grades(count).Text <> "") Then numGrades += 1 courses(count).grade = grades(count).Text courses(count).hours = CDbl(hours(count).Text) End If Next If numGrades > 0 Then 'Redimension the array for the final count. ReDim Preserve courses(count) 'Compute the GPA, and display the result. DisplayGPA(GPA(courses)) Else 'Display the error message. [Page 689] txtOutput.Text = "No grade(s) entered." End If End Sub Function GPA(ByVal c() As Course) As Double 'Compute the GPA of a set of courses. Dim credits, hours As Double 'Add up the credits and hours based upon the grade. For i As Integer = 0 To c.GetUpperBound(0) 'Ignore invalid grades. Select Case c(i).grade.ToUpper Case "A" credits += 4 * c(i).hours hours += c(i).hours Case "B" credits += 3 * c(i).hours hours += c(i).hours Case "C" credits += 2 * c(i).hours hours += c(i).hours Case "D" credits += 1 * c(i).hours hours += c(i).hours Case "F" hours += c(i).hours End Select Next 'The GPA is the points divided by the total credit hours. If hours = 0 Then Return 0 Else Return credits / hours End If End Function Sub DisplayGPA(ByVal gpa As Double) 'Display the GPA and a congratulatory message. txtGPA.Text = FormatNumber(gpa, 2) If gpa >= 3 Then txtOutput.Text = "Congratulations, you made the Honor Roll." Else txtOutput.Text = "Congratulations on completing the semester." End If End Sub | 19. | Structure Building Dim name As String 'Name Dim city As String 'City Dim height As Double 'Height in feet Dim stories As Integer 'Number of stories End Structure Dim buildings(4) As Building 'Holds data Private Sub frmBuildings_Load(...) Handles MyBase.Load 'Load data from file into structure array. Dim count As Integer = 0 Dim sr As IO.StreamReader = IO.File.OpenText("BUILDINGS.TXT") [Page 690] 'Loop until the end of file is reached. Do While sr.Peek <> -1 'Make sure there is enough room to store data. If count > buildings.GetUpperBound(0) + 1 Then ReDim Preserve buildings(count + 5) End If 'Store data from file into structure members. buildings(count - 1).name = sr.ReadLine() buildings(count - 1).city = sr.ReadLine() buildings(count - 1).height = CDbl(sr.ReadLine()) buildings(count - 1).stories = CInt(sr.ReadLine()) count += 1 Loop sr.Close() 'Resize array to exact number stored. ReDim Preserve buildings(count - 1) End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Look up building name, and display information. 'Clear output. txtCity.Clear() txtHeight.Clear() txtStories.Clear() 'Loop over all buildings in the array. For i As Integer = 0 To buildings.GetUpperBound(0) 'If the name matches, display the information. If txtName.Text.ToUpper = buildings(i).name.ToUpper Then txtCity.Text = buildings(i).city txtHeight.Text = CStr(buildings(i).height) txtStories.Text = CStr(buildings(i).stories) End If Next 'If no building matched, then display a message. If txtCity.Text = "" Then MsgBox("Building not found.", 0, "Not found.") End If End Sub | 21. | Structure Franchise Dim name As String 'Franchise Name Dim stores As Integer 'Number of stores End Structure Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Loads data and displays a report on percentage of stores Dim pizza(9) As Franchise Dim count As Integer Dim fmtStr As String = "{0,-20} {1,7:P}" 'Load data into array. pizza(0).name = "Pizza Hut" pizza(0).stores = 7523 pizza(1).name = "Domino's" pizza(1).stores = 4904 pizza(2).name = "Little Caesar's" pizza(2).stores = 2850 pizza(3).name = "Papa John's" [Page 691] pizza(3).stores = 2574 pizza(4).name = "Sbarro" pizza(4).stores = 790 pizza(5).name = "Papa Murphy's" pizza(5).stores = 750 pizza(6).name = "Godfather's" pizza(6).stores = 566 pizza(7).name = "Round Table" pizza(7).stores = 485 pizza(8).name = "CiCi's Pizza pizza(8).stores = 465 pizza(9).name = "Chuck E. Cheese's" pizza(9).stores = 460 'Calculate total number of stores. count = 0 For i As Integer = 0 To 9 count += pizza(i).stores Next 'Display report. lstOutput.Items.Add(String.Format(fmtStr, "NAME", "PERCENT")) For i As Integer = 0 To 9 lstOutput.Items.Add(String.Format(fmtStr, pizza(i).name, _ pizza(i).stores / count)) Next End Sub | Exercises 7.4 1. | 200 100 | 3. | 11 7 Numbers interchanged. | 5. | Items are not properly swapped. | 7. | Sequential, since the array in not ordered | 9. | Four swaps | 11. | (n1) + (n2) + ... + 1. A shorter version of this formula is n*(n1)/2. | 13. | 4 swaps | 15. | 8 comparisons | 17. | 16; 8 1/2; 5 | 19. | Sub SwapThree(ByRef x As String, ByRef y As String, _ ByRef z As String) Dim temp As String temp = x x = y y = z z = temp End Sub | | [Page 692] | 21. | Structure CapitalEvent Dim name As String Dim crowd As Integer 'Estimate in thousands. End Structure Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Read and sort the event data. Dim sr As IO.StreamReader = IO.File.OpenText("7-4-E21.TXT") Dim temp, evt(8) As CapitalEvent 'Nine events total Dim fmtStr As String = "{0,-50} {1,5}" For i As Integer = 0 To 8 evt(i).name = sr.ReadLine() evt(i).crowd = CInt(sr.ReadLine()) Next sr.Close() 'Use bubble sort to order. For i As Integer = 1 To 8 For j As Integer = 1 To 9 - i If evt(j - 1).name > evt(j).name Then 'Swap. temp = evt(j - 1) evt(j - 1) = evt(j) evt(j) = temp End If Next Next 'Display the events. lstOutput.Items.Clear() lstOutput.Items.Add(String.Format(fmtStr, "EVENT", "CROWD")) For i As Integer = 0 To 8 lstOutput.Items.Add(String.Format(fmtStr, evt(i).name, _ evt(i).crowd)) Next End Sub | 23. | Private Sub btnStore_Click(...) Handles btnStore.Click 'Read 10 sorted words, then add one more. Dim i Integer Dim temp, words(10) As String 'Eleven words to store 'Get all eleven words from the user. For j As Integer = 0 To 10 words(j) = InputBox("Enter word #" & "Enter word #" & j + 1, "") Next 'Find correct position of eleventh word. i = 0 Do While words(i) < words(10) i += 1 Loop 'Shift the array, and insert the new word. temp = words(10) For j As Integer = 9 To i Step -1 words(j + 1) = words(j) Next words(i) = temp End Sub | | [Page 693] | 25. | Private Sub btnSort_Click(...) Handles btnSort.Click 'Read and sort a list of numbers Dim n As Integer = CInt(txtN.Text) Dim temp, nums(n - 1) As Double For i As Integer = 0 To n - 1 'Get numbers from the user nums(i) = CDbl(InputBox("Enter number #" & i + 1)) Next 'Use bubble sort to swap For i As Integer = 1 To n - 1 For j As Integer = 1 To n - i If nums(j - 1) > nums(j) Then 'Swap temp = nums(j - 1) nums(j - 1) = nums(j) nums(j) = temp End If Next Next 'Display the ordered list of numbers For i As Integer = 0 To n - 1 1stOutput.Items.Add(nums(i)) Next End Sub | 27. | Dim codes(25) As String Private Sub frmCode_Load(...) Handles MyBase.Load 'Read in the code for the 26 letters of the alphabet. Dim sr As IO.StreamReader = IO.File.OpenText("7-4-E27.TXT") For i As Integer = 0 To 25 codes(i) = sr.ReadLine() Next sr.Close() End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display a word in morse code. Dim word, result As String 'Convert input to uppercase. word = txtWord.Text.ToUpper result = "" 'Loop over each character of the string. Note that the index starts at 0. For i As Integer = 0 To word.Length - 1 If (word.Substring(i, 1) >= "A") And _ (word.Substring(i, 1) <= "Z") Then result = result & codes(Asc(word.Substring(i, 1))_ - Asc("A")) & " " End If Next txtOutput.Text = result End Sub | 29. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Get seven scores from the user, and display the average. Dim scores(6), temp As Integer Dim sum As Integer 'Read the seven scores into the array. [Page 694] For i As Integer = 0 To 6 scores(i) = CInt(InputBox("Enter score #" & i + 1, "")) Next 'Bubble sort the scores. For i As Integer = 1 To 6 For j As Integer = 1 To 7 - i If scores(j - 1) > scores(j) Then 'Swap scores. temp = scores(j - 1) scores(j - 1) = scores(j) scores(j) = temp End If Next Next 'Calculate and display the average. sum = 0 For i As Integer = 2 To 6 'Throw out the two lowest scores. sum += scores(i) Next txtOutput.Text = FormatNumber(sum / 5) End Sub | 31. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Get data from the user, and display the median. Dim data(), temp, median As Double Dim n, p, q As Integer 'Read the number of elements. n = CInt(InputBox("Enter number of data elements:")) ReDim data(n - 1) 'Read the data into the array. For i As Integer = 0 To data.GetUpperBound(0) data(i) = CDbl(InputBox("Enter element #" & (i + 1)) Next 'Bubble sort the data. For i As Integer = 1 To data.GetUpperBound(0) For j As Integer = 1 To data.GetUpperBound(0) + 1 - i If data(j - 1) > data(j) Then 'Swap scores. temp = data(j - 1) data(j - 1) = data(j) data(j) = temp End If Next Next 'Determine median based upon even or odd number of numbers q = data.GetUpperBound(0) + 1 'number of numbers p = CInt(Int((q - 1) / 2)) If Math.Round(q / 2) = q / 2 Then 'If q even, median is average of two middle elements median = (data(p) + data(p + 1)) / 2 Else 'If q odd, median is the middle element median = data(p) End If txtOutput.Text = CStr(median) End Sub | [Page 695]Exercises 7.5 1. | 12 | 3. | Dorothy | 5. | 11 15 | 7. | 1 3 5 | 9. | The declaration statement should read Dim a(3, 2) As Integer. (Once j gets to 3, there will be an "Index Out of Range" error.) | 11. | Sub FillArray(ByRef a() As Double) 'Fill an array. For row As Integer = 0 To 10 For col As Integer = 0 To 10 a(row, col) = col Next Next End Sub | 13. | Sub Exchange(ByRef a() As Double) 'Interchange values of 2nd and 3rd rows. Dim temp As Double For col As Integer = 0 To 10 temp = a(2, col) a(2, col) = a(3, col) a(3, col) = temp Next End Sub | 15. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display a company's inventory from its two stores 'Declare the inventory and sales arrays Dim inventory(,) As Integer = {{25, 64, 23}, {12, 82, 19}} Dim sales(,) As Integer = {{7, 45, 11}, {4, 24, 8}} Dim total(2) As Integer Dim fmtStr As String = "{0,1} {1,2} {2,2} {3,2} {4,3}" 'Adjust the inventory values to reflect todays sales For store As Integer = 1 To 2 For item As Integer = 1 To 3 inventory(store - 1, item - 1) = _ inventory(store - 1, item - 1) - sales(store - 1, item - 1) 'Accumulate the total inventory per store total(store) += inventory(store - 1, item - 1) Next Next 'Display the store's inventory and totals lstOutput.Items.Add(String.Format(fmtStr, "", "1", "2", "3", "TOT")) For store As Integer = 1 To 2 lstOutput.Items.Add(String.Format(fmtStr, store, _ inventory(store - 1, 0), _ inventory(store - 1, 1), _ inventory(store - 1, 2), total(store))) Next End Sub | | [Page 696] | 17. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display the course and campus enrollments 'Define and fill the enrollment array Dim er(,) As Integer = {{5, 15, 22, 21, 12, 25, 16, 11, 17, 23}, _ {11, 23, 51, 25, 32, 35, 32, 52, 25, 21}, _ {2, 12, 32, 32, 25, 26, 29, 12, 15, 11}} 'Define the arrays to accumulate the information Dim campusTotal(2), courseTotal(9) As Integer For campus As Integer = 0 To 2 For course As Integer = 0 To 9 campusTotal(campus) += er(campus, course) courseTotal(course) += er(campus, course) Next Next 'Display the campus enrollment lstOutput.Items.Add("CAMPUS ENROLLMENT") For campus As Integer = 0 To 2 lstOutput.Items.Add(CStr(campus + 1) & ": " & campusTotal(campus)) Next 'Display the course enrollment lstOutput.Items.Add("COURSE ENROLLMENT") For course As Integer = 0 To 9 lstOutput.Items.Add(CStr(course + 1) & ": " & courseTotal(course)) Next End Sub | 19. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Load golf data, cumulate totals, and display results Dim scores(,) As Integer = {{69, 63, 72, 68}, _ {68, 67, 67, 73}, {69, 69, 67, 72}} Dim golfers() As String = {"Tiger Woods", "Luke Donald", _ "Bernhard Langer"} 'Compute the total score for each golfer Dim total(2), rounds(3) As Integer 'Aggregate the figures For golfer As Integer = 0 To 2 For round As Integer = 0 To 3 total(golfer) += scores(golfer, round) rounds(round) += scores(golfer, round) Next Next 'Display golfer's totals lstOutput.Items.Add("GOLFER TOTALS") For golfer As Integer = 0 To 2 lstOutput.Items.Add(golfers(golfer) & ": " & total(golfer)) Next 'Display average per round lstOutput.Items.Add("ROUND AVERAGE") For round As Integer = 0 To 3 lstOutput.Items.Add(round + 1) & ": " & _ FormatNumber(rounds(round) / 3)) Next End Sub | 21. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display the categories of a university [Page 697] Dim ranking(,) As String = _ {{"U of PA", "U of IN", "U of MI", "UC Berk", "U of VA"}, _ {"MIT", "Cng-Mellon", "UC Berk", "Cornell", "U of IL"}, _ {"U of IL", "U of OK", "U of MD", "Cng-Mellon", _ "CO Sch. of Mines"}} Dim categories() As String = {"Business", "Comp Sci.", "Engr/Gen."} 'Look up the specified university in the rankings Dim result As String = "" For category As Integer = 0 To 2 For rank As Integer = 0 To 4 If txtName.Text.ToUpper = ranking(category, rank).ToUpper Then 'Append category name to result result = result & categories(category) & " " End If Next Next 'Display result If result = "" Then txtOutput.Text = "None." Else txtOutput.Text = result End If End Sub | 23. | Dim scores(14, 4) As Integer 'Stores students' exam scores Dim count As Integer 'Current number of students stored Dim names(14) As String 'Stores students' names Private Sub btnAdd_Click(...) Handles btnAdd.Click 'Add student to array. If count = 15 Then MsgBox("Fifteen students already stored", 0, "Warning") Else count += 1 names(count - 1) = txtName.Text scores(count - 1, 0) = CInt(txtExam1.Text) scores(count - 1, 1) = CInt(txtExam2.Text) scores(count - 1, 2) = CInt(txtExam3.Text) scores(count - 1, 3) = CInt(txtExam4.Text) scores(count - 1, 4) = CInt(txtExam5.Text) 'Reset input txtName.Clear() txtExam1.Clear() txtExam2.Clear() txtExam3.Clear() txtExam4.Clear() txtExam5.Clear() txtName.Focus() End If End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Aggregate totals and display report. Dim n, temp As Integer Dim sum, median As Double Dim even As Boolean 'Display student's semester grades. lstOutput.Items.Clear() [Page 698] lstOutput.Items.Add("Students' Semester Average") For i As Integer = 0 To count - 1 'Accumulate sum of scores for each student. sum = 0 For exam As Integer = 0 To 4 sum += scores(i, exam) Next 'Display the student's name and semester average. lstOutput.Items.Add(names(i) & ": " & FormatNumber(sum / 5)) Next 'Display median on the exams. lstOutput.Items.Add("Exam Medians") 'Determine whether the count is even or odd. even = (Int(count / 2) = count / 2) For exam As Integer = 0 To 4 Bubble sort the scores array based upon the exam score. For i As Integer = 1 To count - 1 For j As Integer = 1 To count - i If scores(j - 1, exam) > scores(j, exam) Then 'Swap scores. temp = scores(j - 1, exam) scores(j - 1, exam) = scores(j, exam) scores(j, exam) = temp End If Next Next 'Calculate median depending upon even or odd. n = CInt(Int(count / 2)) If even Then 'Median is average of two middle scores. median = (scores(n - 1, exam) + scores(n, exam)) / 2 Else 'Median is middle score. median = scores(n, exam) End If 'Display median score for exam. lstOutput.Items.Add(exam + 1) & ": " & FormatNumber(median)) Next End Sub | 25. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Load data into an array, cumulate totals, and display a report Dim totalSales As Double Dim sales(,) As Integer = {{25, 64, 23, 45, 14}, _ {12, 82, 19, 34, 63}, _ {54, 22, 17, 43, 35}} Dim price() As Double = {12, 17.95, 95, 86.5, 78} 'Cumulate totals Dim totals(2) As Double [Page 699] For store As Integer = 0 To 2 For item As Integer = 0 To 4 totals(store) += sales(store, item) * price(item) Next Next 'Display report, storing grand total in totalSales lstOutput.Items.Add("Sales per store") For store As Integer = 0 To 2 lstOutput.Items.Add(store + 1 & ": " & FormatCurrency(totals(store))) totalSales += totals(store) Next lstOutput.Items.Add("Total sales: " & FormatCurrency(totalSales)) End Sub | |