[Page 668 (continued)] Exercises 6.1 1. | 17 | 3. | You are a super programmer! | 5. | 2 | 7. | The value of q keeps growing until the program crashes when the value reaches the upper limit for a variable of type Double. | 9. | Do and Loop interchanged | 11. | While num >= 7 | 13. | Until response <> "Y" | 15. | Until name = "" | 17. | Until (a <= 1) Or (a >= 3) | 19. | While n = 0 | 21. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Request and display three names. Dim name As String, num As Integer = 0 Do While num < 3 name = InputBox("Enter a name:") lstOutput.Items.Add(name) num += 1 'Add 1 to value of num. Loop End Sub | 23. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Convert Celsius to Fahrenheit. Dim fmtStr As String = "{0,7} {1,10}" [Page 669] Dim celsius As Double = -40 lstOutput.Items.Add(String.Format(fmtStr, "Celsius", "Fahrenheit")) Do While celsius <= 40 lstOutput.Items.Add(String.Format(fmtStr, celsius, _ Fahrenheit(celsius))) celsius += 5 Loop End Sub Function Fahrenheit(ByVal celsius As Double) As Double 'Convert Celsius to Fahrenheit. Return (9 / 5) * celsius + 32 End Function | 25. | Private Sub btnDetermine_Click(...) Handles btnDetermine.Click 'Determine the year that the world population will exceed '10 billion, assuming a 1.2% rate of increase. Dim yr As Integer, pop As Double yr = 2006 'Start at 2006. pop = 6.5 'Population of 6.5 billion Do While pop <= 10 pop = (1 + 0.012) * pop yr += 1 Loop txtOutput.Text = "The world population will reach 10 billion in " _ & yr & "." End Sub | 27. | Private Sub btnDetermine_Click (. . .) Handles btnDetermine.Click 'Display first terms in the Fibonacci sequence Dim x As Integer = 1 Dim y As Integer = 1 Dim z As Integer = x + y 1stOutput.Items.Clear() 1stOutput.Items.Add(x) 1stOutput.Items.Add(y) Do While z <= 100 1stOutput.Items.Add(z) x = y y = z z = x + y Loop End Sub | 29. | Private Sub btnDetermine_Click(...) Handles btnDetermine.Click 'When after 6:30, do clock hands exactly overlap? Dim minuteHandPos, hourHandPos, difference As Double minuteHandPos = 0 hourHandPos = 30 Do While hourHandPos - minuteHandPos >= 0.0001 difference = hourHandPos - minuteHandPos minuteHandPos = minuteHandPos + difference hourHandPos += difference / 12 Loop txtOutput.Text = "The hands overlap at " & _ FormatNumber(minuteHandPos, 2) & " minutes after six." End Sub | | [Page 670] | 31. | Private Sub btnBounceBall_Click(...) Handles btnBounceBall.Click 'Drop a ball, and find number of bounces and total distance traveled. Dim height, bounceFactor, distance As Double Dim bounces As Integer InputData(height, bounceFactor) BounceBall(height, bounceFactor, bounces, distance) ShowData(bounces, distance) End Sub Sub InputData(ByRef height As Double, _ ByRef bounceFactor As Double) 'Input height and coefficient of restitution. Dim prompt As String prompt = "What is the coefficient of restitution of the " & _ "ball (0 to 1)? Examples are .7 for a tennis ball, " & _ ".75 for a basketball, .9 for a super ball, and " & _ ".3 for a softball." bounceFactor = CDbl(InputBox(prompt)) prompt = "From how many meters will the ball be dropped?" height = CDbl(InputBox(prompt)) height = 100 * height 'Convert to centimeters. End Sub Sub BounceBall(ByVal hght As Double, ByVal bFactor As Double, _ ByRef bounces As Integer, ByRef dist As Double) bounces = 1 'First bounce dist = hght Do While hght * bFactor >= 10 bounces += 1 hght = bFactor * hght dist += 2 * hght 'Up then down again Loop End Sub Sub ShowData(ByVal bounces As Integer, _ ByVal distance As Double) txtOutput.Text = "The ball bounced " & bounces _ & " times and traveled about " & _ FormatNumber(distance / 100) & " meters." End Sub | 33. | Private Sub btnCompute_Click(...) Handles btnCompute.Click 'Calculate number of years to deplete savings account. Dim amt As Double, yrs As Integer amt = CDbl(InputBox("Enter initial amount in account:")) yrs = 0 If amt * 1.05 - 1000 >= amt Then txtOutput.Text = "Account will never be depleted." Else Do amt = amt * 1.05 - 1000 yrs += 1 Loop Until amt <= 0 txtOutput.Text = "It takes " & yrs & _ " years to deplete the account." End If End Sub | | [Page 671] | 35. | Private Sub btnCompute_Click(...) Handles btnCompute.Click 'Compute age when year is the square of age. Dim age As Integer = 1 Do While (1980 + age) <> (age * age) age += 1 Loop txtOutput.Text = age & " years old" End Sub | 37. | Private Sub btnCapitalizeAll_Click(...) Handles btnCapitalizeAll.Click txtOutput.Text = txtSentence.Text.ToUpper End Sub Private Sub btnCapitalizeFirstLetters_Click(...) Handles _ btnCapitalizeFirstLetters.Click 'Capitalize first letter of each word. Dim info As String = txtSentence.Text.Trim Dim word As String Dim newSentence As String = "" Dim positionOfSpace As Integer = info.indexOf(" ") info = txtSentence.Text.Trim Do While info <> "" positionOfSpace = info.IndexOf(" ") If positionOfSpace <> -1 Then word = info.Substring(0, positionOfSpace + 1) info = info.Substring(positionOfSpace + 1) newSentence &= word.Substring(0, 1).ToUpper & word.Substring(1) Else newSentence &= info.Substring(0, 1).ToUpper & info.Substring(1) info = "" End If Loop txtOutput.Text = newSentence End Sub | 39. | Private Sub btnFind_Click(...) Handles btnFind.Click 'Compute the greatest common divisor of two numbers. Dim m, n, t As Integer InputIntegers(m, n) Do While n <> 0 t = n n = m Mod n 'Remainder after m is divided by n. m = t Loop txtOutput.Text = "The greatest common divisor is " & m & "." End Sub Sub InputIntegers(ByRef m As Integer, ByRef n As Integer) 'Input two integers. m = CInt(InputBox("Enter first integer:", "GCD")) n = CInt(InputBox("Enter second integer:", "GCD")) End Sub | [Page 672]Exercises 6.2 1. | At least one word contains the letter A. | 3. | pie cake melon | 5. | A Apple Apricot Avocado B Banana Blueberry G Grape L Lemon Lime | 7. | A brace of ducks. | 9. | counters | 11. | Loop statement missing. Also, loop cannot be entered because the (default) value of num is 0. | 13. | Last president in file will not be displayed. | 15. | Private Sub btnFind_Click(...) Handles btnFind.Click 'Find largest of a collection of numbers. Dim largest, num As Double largest = 0 Dim sr As IO.StreamReader = IO.File.OpenText("POSNUMS.TXT") Do While sr.Peek <> -1 num = CDbl(sr.ReadLine) If num > largest Then largest = num End If Loop txtOutput.Text = "The largest number is " & largest & "." sr.Close() End Sub | 17. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display percentage of grades that are above average. Dim total, grade, average As Double Dim numGrades, aaCount As Integer Dim sr As IO.StreamReader = IO.File.OpenText("FINAL.TXT") total = 0 numGrades = 0 Do While sr.Peek <> -1 grade = CDbl(sr.ReadLine) total += grade numGrades += 1 Loop sr.Close() [Page 673] If numGrades > 0 Then average = total / numGrades aaCount = 0 sr = IO.File.OpenText("FINAL.TXT") Do While sr.Peek <> -1 grade = CDbl(sr.ReadLine) If grade > average Then aaCount += 1 End If Loop sr.Close() txtOutput.Text = FormatPercent(aaCount / numGrades) & _ " of grades are above the average of " & _ FormatNumber(average) & "." End If End Sub | 19. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display the name of the requested president. Dim n, num As Integer Dim name As String Dim sr As IO.StreamReader = IO.File.OpenText("USPRES.TXT") n = CInt(txtPresNum.Text) If (1 <= n) And (n <= 43) Then num = 0 Do name = sr.ReadLine num += 1 Loop Until num = n lstOutput.Items.Add(name & " was President number " & n & ".") sr.Close() End If txtPresNum.Clear() txtPresNum.Focus() End Sub | 21. | Private Sub btnCompute_Click(...) Handles btnCompute.Click 'Generate sequence with algorithm Dim n, numSteps As Double lstOutput.Items.Clear() n = CDbl(txtInitialNumber.Text) numSteps = 0 Do While n <> 1 numSteps += 1 If (n / 2) = Int(n / 2) Then n = n / 2 lstOutput.Items.Add(n) Else n = (3 * n) + 1 lstOutput.Items.Add(n) End If Loop txtOutput.Text = "It took " & numSteps & " steps to reach 1." End Sub | 23. | Private Sub btnFind_Click(...) Handles btnFind.Click 'Analyze a Shakespearean sonnet. Dim totalWords, lineCount As Double [Page 674] Dim wordCount, positionOfSpace As Integer Dim sonnetLine, word As String Dim sr As IO.StreamReader = IO.File.OpenText("SONNET.TXT") totalWords = 0 lineCount = 0 Do While sr.Peek <> -1 sonnetLine = sr.ReadLine lineCount += 1 wordCount = 0 Do While sonnetLine <> "" positionOfSpace = sonnetLine.IndexOf(" ") If positionOfSpace <> -1 Then word = sonnetLine.Substring(0, positionOfSpace + 1) sonnetLine = sonnetLine.Substring(positionOfSpace + 1) Else sonnetLine = "" End If wordCount += 1 Loop totalWords += wordCount Loop sr.Close() txtOutput.Text = "The sonnet contains an average of " & _ FormatNumber(totalWords / lineCount) & _ " words per line and a total of " _ & totalWords & " words." End Sub | 25. | Private Sub btnRemoveParens_Click(...) Handles btnRemoveParens.Click 'Remove parentheses and their contents from a sentence. Dim sentence, letter, newSentence As String Dim parensFlag As Boolean, position As Integer sentence = txtSentence.Text newSentence = "" parensFlag = False position = 0 Do Until position > sentence.Length - 1 letter = sentence.Substring(position, 1) Select Case letter Case "(" parensFlag = True Case ")" parensFlag = False position = position + 1 Case Else If parensFlag = False Then newSentence &= letter End If End Select position += 1 Loop txtOutput.Text = newSentence End Sub | 27. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display liquids available, given an amount of money. Dim money, price As Double [Page 675] Dim liquid, top As String lstOutput.Items.Clear() money = CDbl(txtAmount.Text) top = "You can purchase one gallon of any of the following liquids:" lstOutput.Items.Add(top) Dim sr As IO.StreamReader = IO.File.OpenText("LIQUIDS.TXT") Do While sr.Peek <> -1 liquid = sr.ReadLine price = CDbl(sr.ReadLine) If price <= money Then lstOutput.Items.Add(liquid) End If Loop sr.Close() End Sub | Exercises 6.3 1. | Pass #1 Pass #2 Pass #3 Pass #4 | 3. | 2 4 6 8 Who do we appreciate? | 5. | 5 6 7 | 7. | Steve Cram 3:46.31 Steve Scott 3:51.6 Mary Slaney 4:20.5 | 9. | 1 4 7 10 2 5 8 11 3 6 9 12 | 11. | *******Hooray******* | 13. | Loop is never executed since 1 is less than 25.5, and the step is negative. | 15. | For...Next loop will not execute since 20 is greater than 0. You must add Step -1 to end of For statement. | 17. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click For num As Integer = 1 To 9 Step 2 lstBox.Items.Add(num) Next End Sub | 19. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim row As String = "" For i As Integer = 1 To 9 row &= "*" Next txtOutput.Text = row End Sub | | [Page 676] | 21. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display 10 x 10 array of stars. Dim row As String For i As Integer = 1 To 10 row = "" For j As Integer = 1 To 10 row &= "*" Next lstOutput.Items.Add(row) Next End Sub | 23. | Private Sub btnCompute_Click(...) Handles btnCompute.Click 'Compute the sum 1 + 1/2 + 1/3 + 1/4 + ... + 1/100. Dim sum As Double sum = 0 For denominator As Double = 1 To 100 sum += 1 / denominator Next txtOutput.Text = "The sum is " & FormatNumber(sum, 5) & "." End Sub | 25. | Private Sub btnAnalyzeOptions_Click(...) Handles _ btnAnalyzeOptions.Click 'Compare salaries. Dim opt1, opt2 As Double opt1 = Option1() opt2 = Option2() lstOutput.Items.Add("Option 1 = " & FormatCurrency(opt1)) lstOutput.Items.Add("Option 2 = " & FormatCurrency(opt2)) If opt1 > opt2 Then lstOutput.Items.Add("Option 1 pays better.") Else lstOutput.Items.Add("Option 2 pays better.") End If End Sub Function Option1() As Double 'Compute total salary for 10 days, 'with a flat salary of $100/day. Dim sum As Integer sum = 0 For i As Integer = 1 To 10 sum += 100 Next Return sum End Function Function Option2() As Double 'Compute the total salary for 10 days, 'starting at $1 and doubling each day. Dim sum, daySalary As Integer sum = 0 daySalary = 1 For i As Integer = 1 To 10 sum += daySalary daySalary = 2 * daySalary Next [Page 677] Return sum End Function | 27. | Private Sub btnComputeIdealWeights_Click(...) Handles _ btnComputeIdealWeights.Click 'Ideal weights for men and women Dim lower, upper As Integer lstWeightTable.Items.Clear() InputBounds(lower, upper) ShowWeights(lower, upper) End Sub Function IdealMan(ByVal height As Integer) As Double 'Compute the ideal weight of a man given the height. Return 4 * height - 128 End Function Function IdealWoman(ByVal height As Integer) As Double 'Compute the ideal weight of a woman given the height. Return 3.5 * height - 108 End Function Sub InputBounds(ByRef lower As Integer, ByRef upper As Integer) 'Input the lower and upper bounds on height. lower = CInt(InputBox("Enter lower bound on height in inches:")) upper = CInt(InputBox("Enter upper bound on height in inches:")) End Sub Sub ShowWeights(ByVal lower As Integer, ByVal upper As Integer) 'Display table of weights. Dim fmtStr As String = "{0,-11}{1,-13}{2,-11}" lstWeightTable.Items.Add(String.Format(fmtStr, "Height", _ "Wt-Women", "Wt-Men")) lstWeightTable.Items.Add("") For height As Integer = lower To upper lstWeightTable.Items.Add(String.Format(fmtStr, height, _ IdealWoman(height), IdealMan(height))) Next End Sub | 29. | Private Sub btnAnalyze_Click(...) Handles btnAnalyze.Click 'Determine number of sibilants in sentence. txtOutput.Text = "There are " & Sibilants(txtSentence.Text) & _ " sibilants in the sentence." End Sub Function Sibilants(ByVal sentence As String) As Integer 'Count the number of sibilants (i.e., the letters S and Z). Dim numSibs As Integer Dim letter As String numSibs = 0 For i As Integer = 0 To sentence.Length - 1 letter = sentence.Substring(i, 1).ToUpper If (letter = "S") Or (letter = "Z") Then numSibs += 1 End If Next Return numSibs End Function | | [Page 678] | 31. | Private Sub btnCalculate_Click(...) Handles btnCalculate.Click 'Savings account balance after 10 years Dim amt As Double = 800 For yearNum As Integer = 1 To 10 amt = (1.04 * amt) + 100 '(Growth due to interest) + deposit Next txtOutput.Text = "The final amount is " & FormatCurrency(amt) & "." End Sub | 33. | Private Sub btnAnalyze_Click(...) Handles btnAnalyze.Click 'Radioactive decay; cobalt-60 decays at a rate of about 12% per year Dim grams As Double = 10 For yearNum As Integer = 1 To 5 grams = 0.88 * grams Next lstOutput.Items.Add("Of 10 grams of cobalt-60,") lstOutput.Items.Add(FormatNumber(grams) & _ " grams remain after 5 years.") End Sub | 35. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Draw a hollow box. Dim stars As Integer lstOutput.Items.Clear() stars = CInt(InputBox("Number of stars?")) DrawSide(stars) For i As Integer = 1 To stars - 2 DrawRow(stars) Next DrawSide(stars) End Sub Sub DrawSide(ByVal stars As Integer) 'Draw a solid side of stars for top and bottom. Dim row As String = "" For i As Integer = 1 To stars row &= "*" Next lstOutput.Items.Add(row) End Sub Sub DrawRow(ByVal stars As Integer) 'Draw a row (put spaces between the two stars). Dim row As String = "*" For i As Integer = 1 To stars - 2 row &= " " Next row &= "*" lstOutput.Items.Add(row) End Sub | 37. | Private Sub btnDetermine_Click(...) Handles btnDetermine.Click 'Gambling casino problem Dim testValue, amount As Double testValue = 4 Do testValue += 1 'Start test with $5. amount = testValue [Page 679] For i As Integer = 1 To 3 'One iteration for each casino amount = amount - 1 'Entrance fee amount = amount / 2 'Funds lost amount = amount - 1 'Exit fee Next Loop Until amount = 0 txtOutput.Text = "Beginning amount = " & FormatCurrency(testValue) End Sub | 39. | Private Sub btnCompute_Click(...) Handles btnCompute.Click 'Compute total earnings at retirement 'get 5% raise per year, retire at age 65 Dim name As String, age As Integer, salary As Double Dim earnings As Double = 0 name = InputBox("Enter the person's name: ") age = CInt(InputBox("Enter the person's age: ")) salary = CDbl(InputBox("Enter the person's starting salary: ")) For i As Integer = age To 64 earnings += salary salary = (1.05) * salary Next txtOutput.Text = name & " will earn about " & _ FormatCurrency(earnings, 0) End Sub | |