6.1. Do LoopsA loop, one of the most important structures in Visual Basic, is used to repeat a sequence of statements a number of times. At each repetition, or pass, the statements act upon variables whose values are changing. The Do loop repeats a sequence of statements either as long as or until a certain condition is true. A Do statement precedes the sequence of statements, and a Loop statement follows the sequence of statements. The condition, preceded by either the word "While" or the word "Until", follows the word "Do" or the word "Loop". When Visual Basic executes a Do loop of the form Do While condition statement(s) Loop it first checks the truth value of condition. If condition is false, then the statements inside the loop are not executed, and the program continues with the line after the Loop statement. If condition is true, then the statements inside the loop are executed. When the statement Loop is encountered, the entire process is repeated, beginning with the testing of condition in the Do While statement. In other words, the statements inside the loop are repeatedly executed only as long as (that is, while) the condition is true. Figure 6.1 contains the pseudocode and flowchart for this loop. Figure 6.1. Pseudocode and flowchart for a Do While loop.
Example 1.
Do loops are commonly used to ensure that a proper response is received from the InputBox function. Example 2. |
The following program requires the user to enter a number from 1 through 3. The Do loop repeats the request until the user gives a proper response.
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim response As Integer, quotation As String = "" response = CInt(InputBox("Enter a number from 1 to 3.")) Do While (response < 1) Or (response > 3) response = CInt(InputBox("Enter a number from 1 to 3.")) Loop Select Case response Case 1 quotation = "Plastics." Case 2 quotation = "Rosebud." [Run, and click the button.]
[Type 3 into the box and press the OK button.]
|
In Examples 1 and 2, the condition was checked at the top of the loopthat is, before the statements were executed. Alternatively, the condition can be checked at the bottom of the loop when the statement Loop is reached. When Visual Basic encounters a Do loop of the form
Do statement(s) Loop Until condition
it executes the statements inside the loop and then checks the truth value of condition. If condition is true, then the program continues with the line after the Loop statement. If condition is false, then the entire process is repeated beginning with the Do statement. In other words, the statements inside the loop are executed once and then are repeatedly executed until the condition is true. Figure 6.2 shows the pseudocode and flowchart for this type of Do loop.
The following program is equivalent to Example 2, except that the condition is tested at the bottom of the loop: Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim response As Integer, quotation As String = "" Do response = CInt(InputBox("Enter a number from 1 to 3.")) Loop Until (response >= 1) And (response <= 3) Select Case response Case 1 quotation = "Plastics." Case 2 quotation = "Rosebud." Case 3 quotation = "That's all folks." End Select txtQuotation.Text = quotation End Sub |
Do loops allow us to calculate useful quantities for which we might not know a simple formula.
Suppose you deposit money into a savings account and let it accumulate at 6 percent interest compounded annually. The following program determines when you will be a millionaire:
Private Sub btnYears_Click(...) Handles btnYears.Click 'Compute years required to become a millionaire Dim balance AsDouble, numYears As Integer balance = CDbl(txtAmount.Text) DoWhile balance < 1000000 balance += 0.06 * balance numYears += 1 Loop txtWhen.Text = "In " & numYears & _ " years you will have a million dollars." End Sub [Run, type 100000 into the text box, and press the button.]
|
Be careful to avoid infinite loopsthat is, loops that are never exited. The following loop is infinite, because the condition "balance < 1000" will always be true.
Note: Click on the form's Close button at the upper right corner of the title bar to end the program.
Private Sub btnButton_Click(...) Handles btnlick 'An infinite loop Dim balance As Double = 100, intRate As Double Do While balance < 1000 balance = (1 + intRate) * balance Loop txtBalance.Text = FormatCurrency(balance) End Sub
Notice that this slip-up can be avoided by adding something like = 0.04 to the end of the Dim statement.
Visual Basic allows the use of the words "While" and "Until" at either the top or bottom of a Do loop. In this text, the usage of these words is restricted for the following reasons:
Because any While statement can be easily converted to an Until statement and vice versa, the restriction produces no loss of capabilities and the programmer has one less matter to think about.
Restricting the use simplifies reading the program. The word "While" proclaims testing at the top, and the word "Until" proclaims testing at the bottom.
Certain other major structured languages only allow "While" at the top and "Until" at the bottom of a loop. Therefore, following this convention will make life easier for people already familiar with or planning to learn one of these languages.
Standard pseudocode uses the word "While" to denote testing a loop at the top and the word "Until" to denote testing at the bottom.
1. | How do you decide whether a condition should be checked at the top of a loop or at the bottom? |
2. | Change the following code segment so it will be executed at least once: Do While continue = "Yes" answer = InputBox("Do you want to continue? (Y or N)") If answer.ToUpper = "Y" Then continue = "Yes" Else continue = "No" End If Loop |
In Exercises 1 through 6, determine the output displayed when the button is clicked.
1. |
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim q As Double q = 3 Do While q < 15 q = 2 * q - 1 Loop txtOutput.Text = CStr(q) End Sub |
2. |
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim balance As Double = 1000 Dim interest As Double = 0.1 Dim n As Integer = 0 'Number of years Do lstOutput.Items.Add(n & " " & balance) balance = (1 + interest) * balance n += 1 Loop Until (balance > 1200) lstOutput.Items.Add(n) End Sub |
3. |
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display a message Dim num As Double = 4 Dim message As String = "" Do Select Case num Case 1 message = "grammer!" num = -1 Case 2 message = "re a su" num = (5 - num) * (3 - num) Case 3 message = "per pro" num = 4 - num Case 4 message = "You a" num = 2 * num - 6 End Select txtOutput.Text &= message Loop Until (num = -1) End Sub |
4. |
Private Sub btnQuiz_Click(...) Handles btnQuiz.Click Dim prompt As String, firstYear As Integer 'Computer-assisted instruction prompt = "In what year was the IBM PC first produced?" lstQuiz.Items.Clear() Do firstYear = CInt(InputBox(prompt)) Select Case firstYear Case 1981 lstQuiz.Items.Add("Correct. The computer was an instant") lstQuiz.Items.Add("success. By the end of 1981, there") lstQuiz.Items.Add("was such a backlog of orders that buyers") lstQuiz.Items.Add("had a three-month waiting period.") (Assume that the first response is 1980 and the second response is 1981.) |
5. |
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Calculate the remainder in long division txtOutput.Text = CStr(Remainder(3, 17)) End Sub Function Remainder(ByVal divisor As Double, _ ByVal dividend As Double) As Double Dim sum As Double = 0 Do While sum <= dividend sum += divisor Loop Return (dividend - sum + divisor) End Function |
6. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Simulate IndexOf; search for the letter t Dim info As String = "Potato" Dim letter As String = "t" Dim answer As Integer answer = IndexOf(info, letter) txtOutput.Text = CStr(answer) End Sub Function IndexOf(ByVal word As String, ByVal letter As String) _ As Integer Dim counter As Integer = 0 Dim current As String = "" Do While counter < word.Length current = word.Substring(counter, 1) If letter = current Then Return counter End If counter += 1 'Add 1 to the value of counter Loop 'If not found then the answer is -1 Return -1 End Function |
In Exercises 7 through 10, identify the errors.
7. |
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim q As Double q = 1 Do While q > 0 q = 3 * q - 1 lstOutput.Items.Add(q) Loop End Sub |
8. |
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display the numbers from 1 to 5 Dim num As Integer Do While num <> 6 num = 1 lstOutput.Items.Add(num) num += 1 Loop End Sub |
9. |
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Repeat until a yes response is given Dim answer As String = "N" Loop answer = InputBox("Did you chop down the cherry tree (Y/N)?") Do Until (answer.ToUpper = "Y") End Sub |
10. |
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Repeat as long as desired Dim n As Integer, answer As String = "" Do n += 1 lstOutput.Items.Add(n) answer = InputBox("Do you want to continue (Y/N)?") Until answer.ToUpper = "N" End Sub |
In Exercises 11 through 20, replace each phrase containing "Until" with an equivalent phrase containing "While", and vice versa. For instance, the phrase (Until sum = 100) would be replaced by (While sum <> 100).
11. | Until num < 7 |
12. | Until name = "Bob" |
13. | While response = "Y" |
14. | While total = 10 |
15. | While name <> "" |
16. | Until balance >= 100 |
17. | While (a > 1) And (a < 3) |
18. | Until (ans = "") Or (n = 0) |
19. | Until Not (n = 0) |
20. | While (ans = "Y") And (n < 7) |
In Exercises 21 and 22, write simpler and clearer code that performs the same task as the given code.
21. |
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim name As String name = InputBox("Enter a name:") lstOutput.Items.Add(name) name = InputBox("Enter a name:") lstOutput.Items.Add(name) name = InputBox("Enter a name:") lstOutput.Items.Add(name) End Sub |
22. |
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim loopNum As Integer, answer As String = "" Do If loopNum >= 1 Then answer = InputBox("Do you want to continue (Y/N)?") answer = answer.ToUpper Else answer = "Y" End If If (answer = "Y") Or (loopNum = 0) Then loopNum += 1 txtOutput.Text = CStr(loopNum) End If Loop Until (answer <> "Y") End Sub |
23. | Write a program that displays a Celsius-to-Fahrenheit conversion table. Entries in the table should range from -40 to 40 degrees Celsius in increments of 5 degrees. Note: The formula f = (9/5)*c + 32 converts Celsius to Fahrenheit. |
24. | The world population doubled from 3 billion in 1959 to 6 billion in 1999. Assuming that the world population has been doubling every 40 years, write a program to determine when in the past the world population was less than 6 million. |
25. | The world population reached 6.5 billion people in 2006 and was growing at the rate of 1.2 percent each year. Assuming that the population will continue to grow at the same rate, write a program to determine when the population will reach 10 billion. |
26. | Write a program to display all the numbers between 1 and 100 that are perfect squares. (A perfect square is an integer that is the square of another integer; 1, 4, 9, and 16 are examples of perfect squares.) |
27. | Write a program to display all the numbers between 1 and 100 that are part of the Fibonacci sequence. The Fibonacci sequence begins 1, 1, 2, 3, 5, 8,..., where each new number in the sequence is found by adding the previous two numbers in the sequence. |
28. | Write a program to request positive numbers one at a time from the user in an input dialog box. The user should be instructed to enter -1 after all the positive numbers have been supplied. At that time, the program should display the sum of the numbers. |
29. | An old grandfather clock reads 6:00 p.m. Sometime not too long after 6:30 p.m., the minute hand will pass directly over the hour hand. Write a program using a loop to make better and better guesses as to what time it is when the hands exactly overlap. Keep track of the positions of both hands using the minutes at which they are pointing. (At 6:00 p.m., the minute hand points at 0 while the hour hand points at 30.) You will need to use the fact that when the minute hand advances m minutes, the hour hand advances m/12 minutes. (For example, when the minute hand advances 60 minutes, the hour hand advances 5 minutes from one hour mark to the next.) To make an approximation, record how far the minute hand is behind the hour hand, then advance the minute hand by this much and the hour hand by 1/12 this much. The loop should terminate when the resulting positions of the minute and hour hands differ by less than .0001 minute. (The exact answer is 32 and 8/11 minutes after 6.) |
30. | Write a program that requests a word containing the two letters r and n as input and determines which of the two letters appears first. If the word does not contain both of the letters, the program should so advise the user. (Test the program with the words "colonel" and "merriment.") |
31. | The coefficient of restitution of a ball, a number between 0 and 1, specifies how much energy is conserved when a ball hits a rigid surface. A coefficient of .9, for instance, means a bouncing ball will rise to 90 percent of its previous height after each bounce. Write a program to input a coefficient of restitution and an initial height in meters, and report how many times a ball bounces when dropped from its initial height before it rises to a height of less than 10 centimeters. Also report the total distance traveled by the ball before this point. The coefficients of restitution of a tennis ball, basketball, super ball, and softball are .7, .75, .9, and .3, respectively. |
In Exercises 32 through 35, write a program to solve the stated problem.
32. | Savings Account. $15,000 is deposited into a savings account paying 5 percent interest and $1000 is withdrawn from the account at the end of each year. Approximately how many years are required for the savings account to be depleted? Note: If at the end of a certain year the balance is $1000 or less, then the final withdrawal will consist of that balance and the account will be depleted. | ||||||||||||||||||||||||||||||||||||||||||
33. | Rework Exercise 32 so that the amount of money deposited initially is input by the user and the program computes the number of years required to deplete the account. Note: Be careful to avoid an infinite loop. | ||||||||||||||||||||||||||||||||||||||||||
34. | Consider an account in which $1000 is deposited upon opening the account and an additional $1000 is deposited at the end of each year. If the money earns interest at the rate of 5 percent, how long will it take before the account contains at least $1 million? | ||||||||||||||||||||||||||||||||||||||||||
35. | A person born in 1980 can claim, "I will be x years old in the year x squared." Write a program to determine the value of x. | ||||||||||||||||||||||||||||||||||||||||||
36. | Illustrate the growth of money in a savings account. When the user presses the button, values for Amount and Interest Rate are obtained from text boxes and used to calculate the number of years until the money doubles and the number of years until the money reaches a million dollars. Use the form design shown below. Note: The balance at the end of each year is (1 + r) times the previous balance, where r is the annual rate of interest in decimal form.
| ||||||||||||||||||||||||||||||||||||||||||
37. | Allow the user to enter a sentence. Then, depending on which button the user clicks, display the sentence entirely in capital letters or with just the first letter of each word capitalized. |
In Exercises 38 and 39, write a program corresponding to the flowchart.
38. | The flowchart in Figure 6.3 (on the next page) requests a whole number greater than 1 as input and factors it into a product of prime numbers. Note: A number is prime if its only factors are 1 and itself. Test the program with the numbers 660 and 139. Figure 6.3. Prime factors. |
39. | The flowchart in Figure 6.4 (on page 261) finds the greatest common divisor (the largest integer that divides both) of two positive integers input by the user. Write a program that corresponds to the flowchart. Use the Visual Basic operator Mod. The value of m Mod n is the remainder when m is divided by n. Figure 6.4. Greatest common divisor. |
1. | As a rule of thumb, the condition is checked at the bottom if the loop should be executed at least once. |
2. | Either precede the loop with the statement continue = "Yes", or change the first line to Do and replace the Loop statement with Loop Until continue <> "Yes". |