Now you're really ready to write powerful programs! You've
learned some controls, you've defined some variables, and you've written programs that make decisions. It's now time to learn how to write programs that perform repetitive data
processing. When a computer does something over and over, the computer is said
to be looping.
Computers don't get bored. The primary strength of computers is their capability to loop through a series of calculations over and over very quickly. Computers can process every customer balance, calculate sales averages
among many divisions, and
display data for each company employee.
This unit describes how you can add looping to Visual Basic programs so that the programs can process several data values using looping statements. Loops don't just help when you
have large amounts of data to process. Loops also enable you to correct
user errors and repeat certain program functions when the user requests a repeat.
Concept: The Do statement supports several different loop formats. The Do While loop is perhaps the most common looping statement that you'll put in
Visual Basic programs.
Definition: A block consists of one or more program statements.
The Do While statement
works with relational expressions just as the If statement does. Therefore, the six relational operators that you learned about in the previous lesson work as expected here. Rather than control the one-time execution of a single
block of code, however,
the relational expression controls the looping statements.
The code that you've seen so far inside event procedures has been sequential code that executed one statement following another in the order that you typed the statements. Looping changes
things a bit. Many lines of your programs will still execute
sequentially, but a loop will cause blocks of code to repeat one or more times.
Like the If statement that ends with an End If statement, a loop will always be a multiline statement
that includes an obvious beginning and ending of the loop. Here is the format of the Do While loop:
Do While (relational test) Block of one or more Visual Basic statements Loop
Definition: An infinite loop repeats forever.
The block of code continues looping as long as the relational test is true. Whether you insert
one or several lines of code for the block doesn't matter. It's vital, however, that the block of code somehow change a variable used in the
relational test. The block of code keeps repeating as long as the Do While loop's relational
test continues to stay true. Eventually, the relational test must become false or your program will enter an infinite loop and the user
will have to break the program's execution through an inelegant means, such as pressing the
Ctrl+Break key combination.
Warning: Even if you provide an Exit command button as you've seen used in this book's applications, the program will often ignore the user's Exit command button click if the program enters an infinite loop.
Figure 10.1 illustrates how the Do While loop works. As long as the relational test is true, the block of code in the body of the
loop continues executing. When the relational test becomes false, the loop terminates. After the loop
terminates, Visual Basic begins program execution at the statement following the Loop statement because Loop signals the end of the loop.
Figure 10.1. The Do While loop's action continues while the relational test is true.
Note: As soon as the relational test becomes false, the loop terminates and doesn't execute even one more time. The Do While's relational test appears at the top of the loop. Therefore, if the relational test is false the first time that the loop begins, the body of the loop will never execute.
Throughout this book, you'll see indention used for the body of the loop code. By indenting the body of the loop to
the right of the loop's introduction and terminating statements, you'll make it easier to spot where the loop begins and ends.
Stop and Type: Listing 10.1 contains a section of an event procedure that
contains a Do While loop that asks the user for an age. If the user enters an age less than 10 or more than 99, the program beeps at the
error and displays another input box asking for the age. The program continues looping, asking for the age, as long as
the user enters an age that's out of range.
Review: The Do While loop continues executing a block of Visual Basic statements as long as a relational test is true. As soon as the relational
test becomes false, the loop terminates.
Listing 10.1. The Do While loop executes as long as the relational test is true.
1: Dim StrAge As String 2: Dim Age As Integer 3: ' Get the age in a string variable 4: StrAge = InputBox$("How old are you?", "Age Ask") 5: ' Check for the Cancel command button 6: If (StrAge = "") Then 7: End 8: End If 9: ' Cancel was not pressed, so convert Age to integer 10: Age = Val(StrAge) 11: ' Loop if the age is not in the correct range 12: Do While ((Age < 10) Or (Age > 99)) 13: ' The user's age is out of range 14: Beep 15: MsgBox "Your age must be between 10 and 99", MB_ICONEXCLAMATION, "Error!" 16: StrAge = InputBox("How old are you?", "Age Ask") 17: ' Check for the Cancel command button 18: If (StrAge = "") Then 19: End 20: End If 21: Age = Val(StrAge) 22: Loop
Output: Figure 10.2 shows the message box error displayed in line 15 if the user enters an age value that's less than 10 or more than 99.
Figure 10.2. The user sees this message box as long as the age is out of range.
Analysis: Lines 1 and 2 define two variables, a string and an integer. The code uses the
string variable to capture the return value from the InputBox$() function. Use a string variable so that you can test for
the Cancel button because, as you learned in the previous lesson, InputBox$() returns a null string if the user presses Cancel. If
the user presses Cancel, the code terminates the entire program with an End statement (lines 7 and 19). If the user enters an
age (and did not press Cancel), the code converts the string age to an integer and checks to make sure that the age is within the
range of 10 to 99.
Line 12 begins a loop if the age is less than 10 or more than 99. The loop continues executing from line 13 to the end of the loop in line 22. If the age is out of range, the body of the loop executes. Line 14 beeps, thus
sending an audible signal to
the user that something is wrong. Line 15 displays an error message box (the one shown in Figure 10.2) and after the user presses OK at the message box, the user is once again asked for an age with an InputBox$() function
shown on line 16. The loop then
checks to make sure that the user didn't press Cancel (lines 17 through 20) and, if not, the code converts the string age to an integer and the loop begins once again. If the age entered in the previous pass of the loop
falls within the valid age range,
the program finishes (any code that exists past line 22 executes). Otherwise, the loop begins once again.
The code contains some redundancy. For example, lines 4 and 16 contain almost the same InputBox$()
function, and the same check for a Cancel command button press appears twice in the program. There are other looping statements that you'll learn about
later in this chapter; those statements can help simplify this code by removing some of the redundancy.
Perhaps the most important thing to note about the Do While loop in Listing 10.1 is that the body of the loop provides a way for the relational test to terminate. Line 12's relational test uses the Age variable that the body of the
loop
reassigns each time the loop's block of code executes. Therefore, assuming that the user enters a different value for the age, the loop will test against a different set of relational values in line 12 and, it is hoped, the relational test will fail
(which
would mean that the age is inside the range) and the program will stop looping. If the loop body did nothing with the relational test variable, the loop would continue forever.
Concept: Whereas the Do While loop continues executing the body of the loop as long as the relational test
is true, the Do Until loop executes the body of the loop as long as the relational test
is false. The program's logic at the time of the loop determines which kind of loop works best in a given situation.
The Do Until loop works almost
exactly like the Do While except that the Do Until loop continues executing the body of the loop until the relational test is true. Like the Do While, the Do Until is a multiline looping statement that can
execute a block of code that's one
or more lines long.
Here is the format of the Do Until:
Do Until (relational test) Block of one or more Visual Basic statements Loop
Again, keep in mind that the relational test must
be false for the loop to continue. Figure 10.3 illustrates how the Do Until works.
Figure 10.3. The Do Until loop's action continues while the relational
test is false.
Stop and Type: You can use the Do While or the Do Until for almost any loop. Listing 10.2 contains the age-checking event procedure that contains a Do Until loop.
The loop ensures that the age falls between two
values. As you can see, the relational test for the Do Until is the opposite of that used in Listing 10.1's Do While loop.
Note: Use the loop that makes for the cleanest and clearest relational test. Sometimes, the logic makes the Do While clearer, whereas other loops seem to work better when you set them up with the Do Until loop.
Review: The Do Until loop continues executing a block of Visual Basic statements as long as a relational test is false. As soon as the relational test becomes true (the
loop is said to Do a
loop until the condition becomes false), the loop terminates and the program continues on the line that follows the closing Loop statement.
Listing 10.2. The Do Until
loops until the relational test becomes true.
1: Dim StrAge As String 2: Dim Age As Integer 3: ' Get the age in a string variable 4: StrAge = InputBox$("How old are you?", "Age Ask") 5: ' Check for the Cancel command button 6: If (StrAge = "") Then 7: End 8: End If 9: ' Cancel was not pressed, so convert Age to integer 10: Age = Val(StrAge) 11: ' Loop if the age is not in the correct range 12: Do Until ((Age >= 10) And (Age <= 99)) 13: ' The user's age is out of range 14: Beep 15: MsgBox "Your age must be between 10 and 99", MB_ICONEXCLAMATION, "Error!" 16: StrAge = InputBox("How old are you?", "Age Ask") 17: ' Check for the Cancel command button 18: If (StrAge = "") Then 19: End 20: End If 21: Age = Val(StrAge) 22: Loop
Analysis:
Line 12 is the only line that marks the difference between Listing 10.1 and 10.2. The age must now fall within the valid range for the loop to terminate.
Note: There is really no advantage of using Do While or Do Until. Use whichever one seems to flow the best for any given application.
Concept: There is another pair of Do loops that works almost exactly like the two previous sections' loops. Do-Loop While and
the Do-Loop Until look very much like their counterparts that you learned earlier.
Nevertheless, these new loop formats check their relational tests at the bottom of the loop rather than at the top.
If a loop begins with a single Do
statement, the loop ends with either Loop While or Loop Until. Here is the format of the Do-Loop While:
Do Block of one or more Visual Basic statements Loop Until (relational test)
Tip: The dash in Do-Loop While serves to remind you that the body of the loop comes before the Loop While statement. The dash in the Do-Loop Until performs the same purpose.
That Do looks lonely by itself, doesn't it? Figure 10.4 illustrates the flow of the Do-Loop While loop's execution.
Figure 10.4. The Do-Loop While loop doesn't check for the relational test until the bottom of the loop
body.
Notice that the Do-Loop While loop's
relational test appears at the bottom of the loop instead of at the top of the loop. You'll use the Do-Loop While loop when you want the body of the loop to execute at least one time. Often, by
placing the relational test at
the bottom of the loop, you can eliminate redundant code that otherwise might be required if you used Do While.
To complete the loop statements, Visual Basic also supports a Do-Loop Until statement. Like the Do-Loop While, the Do-Loop Until
statement tests the relational test at the bottom of the loop. Therefore, the body of the loop executes at least once
no matter what the relational test turns out to be. The loop continues as long as the relational test remains
false. Figure 10.5 illustrates the action of the Do-Loop Until.
Figure 10.5. The Do-Loop Until loop checks for a false relational test at the bottom of the loop
body.
Stop and Type: Listing 10.3 contains the age-checking event procedure that's much shorter than the
previous versions. The relational test appears at the bottom of the loop, so the extra InputBox$()
function call is not needed.
Review: The relational test appears at the bottom of the
loop if you use the Do-Loop While loop statement. The body of the loop always executes at least once. The body of the loop executes more than once
as long as the relational test stays true. There is a corresponding Do-Loop Until statement that
checks for a false condition at the bottom of the loop's body.
Listing 10.3. Use the Do-Loop While to check the relation at the bottom of the loop.
1: Dim StrAge As String 2: Dim Age As Integer 3: Do 4: StrAge = InputBox("How old are you?", "Age Ask") 5: ' Check for the Cancel command button 6: If (StrAge = "") Then 7: End 8: End If 9: Age = Val(StrAge) 10: If ((Age < 10) Or (Age > 99)) Then 11: ' The user's age is out of range 12: Beep 13: MsgBox "Your age must be between 10 and 99", MB_ICONEXCLAMATION, "Error!" 14: End If 15: Loop While ((Age < 10) Or (Age > 99))
Analysis: The loop begins almost immediately in line 3. The loop's body will always execute at least once, so the InputBox$() appears right inside the loop. By placing the
InputBox$() function inside the
loop, you eliminate the need to put this function in the code twice (once before the loop and once inside the loop, as was necessary using the previous looping statements in Listings 10.1 and 10.2).
Line 10 must
check to make sure that the InputBox$() value is in or out of the age range so that the message box error can be displayed.
Note: In this simple application of the looping statements that you've seen here, the Do-While loop required less code than the Do While and Do Until loops. By changing line 15's relational test, a Do Until would also work. These last two loops will not, in every case, produce less code. The logic of the application determines which loop works best.
Concept: The For loop (sometimes called the For-Next loop) also creates a loop. Unlike the Do loops, however, the For loop repeats for a specified number of times. The format of the For loop looks a little more
daunting than the Do loops, but after you master the format, you'll have little trouble implementing For loops when your code needs to repeat a section of code for a specified number of times.
There isn't one correct loop to use in all
situations. The For statement provides the mechanism for the fifth Visual Basic loop construction that you'll learn. A For loop always begins with the For statement and ends with the Next statement. Here is the
format of the For loop:
For CounterVar = StartVal To EndVal [Step IncrementVal] Block of one or more Visual Basic statements Next CounterVar
The loop in Listing 10.4 computes the total of the numbers from 1 to 10.
Listing 10.4. Add the numbers from 1 to 10.
1: Sum = 0 2: For Number = 1 To 10 3: Sum = Sum + Number 4: Next Number
Number is the CounterVar in the For's format
(line 2). The CounterVar must be a variable. 1 is the StartVal (line 2). The StartVal can be either a Number, expression, or variable. 10 is the EndVal (still in line 2).
The EndVal can be either a Number, expression, or
variable. There is no Step specified here. In the For statement's format, the Step IncrementVal is optional. If you don't specify a Step value, Visual Basic assumes a Step value of 1.
Therefore, both of the following For statements are exactly the
same:
For Number = 1 To 10
and
For Number = 1 To 10 Step 1
Listing 10.4's summing For loop initially assigns to the CounterVar the
StartVal in line 2. Therefore, Number is assigned 1 at the top of the loop. Visual Basic then executes the body of the loop using the value of 1 for Number. With
Number being equal to 1, line 3 works as follows the first time through the loop:
Sum = Sum + 1
When Visual Basic executes the Next Number statement, Visual Basic returns to the top of the loop (the For statement), adds the Step value of 1 to Number, and continues the loop again
using 2 as Number in the loop's body. Therefore, the second time
through the loop, line 3 works as follows:
Sum = Sum + 2
The loop continues, adding the default Step value of 1 to Number each time
that the loop executes. When Number becomes 10 (the EndVal), the loop finishes and the statement following the Next statement continues.
Tip: Remember, the For loop terminates when the CounterVar becomes larger than the EndVal. There's an exception to this: If you code a negative Step value, the loop terminates when the CounterVar becomes smaller than the EndVal, as you'll see a little later in this section.
You don't need the For statement to sum the values of 1 through 10. You could code one long assignment statement like this:
Sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
You could also code back-to-back assignment statements like this:
Sum = Sum + 1 Sum = Sum + 2 Sum = Sum + 3 Sum = Sum + 4 Sum = Sum + 5 Sum = Sum + 6 Sum = Sum + 7 Sum = Sum + 8 Sum = Sum + 9 Sum = Sum + 10
Neither of these approaches is extremely difficult, but what if you needed to add together the first one hundred integer Numbers? The previous assignments could become tedious indeed, but the For loop
to add the first one hundred integers is just as
easy to code as for the first 10 integers, as Listing 10.5 demonstrates.
Listing 10.5. Add the Numbers from 1 to 100.
1: Sum = 0 2: For Number = 1 To 100 ' Only this line changes 3: Sum = Sum + Number 4: Next Number
The following loop displays five message boxes:
For c = 1 To 20 Step 4 MsgBox "This is a message box" Next c
Definition: A loop iteration is one full loop cycle.
The loop counts up from 1 to 20 by
4s, putting each count into the variable named c and printing a message box each time. The Step value changes how Visual Basic updates the CounterVar each time that the loop iterates.
If you specify a negative Step value, Visual Basic
counts down. The following loop rings the PC's speaker five times:
For i = 5 To 1 Step -1 Beep Next i
Warning: If you specify a negative Step value, the EndVal must be less than the StartVal or Visual Basic will execute the loop only once.
You Can Terminate Loops Early: Sometimes, you'll be processing user input or several data values using looping statements, and an exception occurs in the data that requires an immediate termination of the loop. For example, you may be collecting sales values for a company's ten divisions inside a For loop that iterates ten times. However, the user can enter zero for a division's sales value, indicating that there is no sales data for that division. Rather than complete the loop, your program might need to quit the loop at that point because the full divisional report information can't be gathered at the time.
The Exit Do and the Exit For statements automatically terminate loops. No matter what the Do loop's relational test results in, or no matter how many more iterations are left in a For loop, when Visual Basic encounters an Exit Do or Exit For statement, Visual Basic immediately quits the loop and sends execution down to the statement following the loop.
Typically, an If statement triggers one of the Exit statements like this:
For Divisions = 1 To 10
' Code to get a sales value
If (sales = 0) Then
Exit For ' Quit the loop early
End If
' Process the rest of the code
Next Divisions
The If ensures that the Exit For executes only under one specific condition (a missing sales value). Without that specific condition triggering the Exit For, the loop cycles normally.
Stop
and Type: Listing 10.6 contains a fairly comprehensive For loop that computes compound interest for an initial investment of $1,000.00. The code appears inside the Click event procedure for a command
button named cmdInt. In case you're not
familiar with compound interest, each year the amount of money invested, including interest earned so far, compounds to build more money. Each time period, normally a year, means that another year's interest must be
added to the value of the investment. A
For loop is perfect for calculating interest. Listing 10.6 uses five compound cycles.
Review: The For loop repeats a block of one or more statements of Visual Basic code. Unlike the Do loops, the For
loop iterates for a specified Number of times as controlled by the For statement's control
values and variables.
Listing 10.6. Using a For loop to calculate compound interest.
1: Sub cmdInt_Click () 2: ' Use a For loop to calculate a final total 3: ' investment using compound interest. 4: ' Num is a loop control variable 5: ' IRate is the annual interest rate 6: ' Term is the Number of years in the investment 7: ' InitInv is the investor's initial investment 8: ' Interest is the total interest paid 9: Dim IRate, Interest As Single 10: Dim Term, Num As Integer 11: Dim InitInv As Currency 12: 13: IRate = .08 14: Term = 5 15: InitInv = 1000.00 16: Interest = 1 ' Begin at one for first compound 17: 18: ' Use loop to calculate total compound amount 19: For Num = 1 To Term 20: Interest = Interest * (1 + IRate) 21: Next 22: 23: ' Now we have total interest, 24: ' calculate the total investment 25: ' at the end of N years 26: lblFinalInv.Caption = InitInv * Interest 27: End Sub
Analysis: This analysis focuses on the loop and not the interest calculation. The most important
thing that you can do at this point is to master the For looping statement. Lines 1 through 8 contain fairly
extensive remarks. The remarks contain variable descriptions so that anyone looking at the code or changing the code later will know what the
variables are for.
After the program defines all the variables in lines 9 through 11, the variables are initialized with start-up values in lines 13 through 16. If you use this event procedure, be sure to add a label named lblFinalInv to a form
and add a command button to
the form named cmdInt. Line 15 will seem to give you trouble as you type it unless you remember Lesson 2's description of data suffix characters. Visual Basic uses the pound sign, #, to indicate double-precision values, and
Visual Basic will assume that
1000.00 is a double-precision value (I don't know why) and will convert the 1000.00 to 1000# right after you press Enter at the end of the line! Don't worry about Visual Basic's pickiness here.
The most important
part of this program appears on lines 19 through 21. Line 19 begins a For loop that iterates through each interest rate period (five of them), compounding the interest on top of the investment to date on line 20. Again, don't let the
finance worry you.
The calculation is less important than understanding the looping process. After the loop finishes, line 26 completes the event procedure by placing the compounded investment in the label. By the way, if you do implement this event
procedure in your own
application, the investment will appear in the window as a double-precision Number with several decimal places showing. You'll learn how to format the data into dollars and cents in lesson 7.
A
nested loop is a loop within a loop. The outer loop determines how many times the inner loop executes. See whether you can determine how many times the following code beeps the user.
For i = 1 To 5 ' The outer loop
For j = 1 To 3 ' The
inner loop
Beep
Next j ' Inner loop completes before
Next i ' outer loop iterates again