You've now mastered sequential logic and decision-making logic. This hour's lesson explains how to write programs that contain looping logic. A loop is a set of program instructions that execute repeatedly. Your programming preferences and application dictate how many times the loop must repeat.
Loops play important roles in programs because you'll need to repeat sections of a program to process multiple data values. For example, you may need to calculate a total of past due charges for all past due customers. A loop can read each customer's past-due charge and add that amount to the running total. As you learn more about Visual Basic in subsequent lessons, you will see additional uses for loops.
The highlights of this hour include
Visual Basic supports several versions of the Do statement. The Do While loop is perhaps the most common looping statement that you'll put in Visual Basic programs. Do While works with comparison expressions just as the If statement does. Therefore, the six comparison 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 comparison expression controls the looping statements.
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 (comparison test) Block of one or more Visual Basic statements Loop
The block of code continues looping as long as comparison 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 comparison test. The block of code keeps repeating as long as the Do While loop's comparison test continues to stay true. Eventually, comparison 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.
New Term: An infinite loop is a loop that never terminates.
WARNING: Guard against infinite loops and always make sure your loops can terminate properly. Even if you provide an Exit command button or a File|Exit menu option in your application, the program will often ignore the user's exit command if the program enters an infinite loop.
The Do While loop continues executing a block of Visual Basic statements as long as comparison test is true. As soon as comparison test becomes false, the loop terminates.
As long as comparison test is true, the block of code in the body of the loop
continues executing. When comparison 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. As
soon as Do While's comparison test becomes false, the loop terminates and
doesn't execute even one more time. The Do While's comparison test appears
at the top of the loop. Therefore, if comparison test is false the first time the
loop begins, the body of the loop will never execute.
Listing 8.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.
Dim strAge As String Dim intAge As Integer Dim intPress As Integer ` Get the age in a string variable strAge = InputBox("How old are you?", "Age Ask") ` Check for the Cancel command button If (strAge = "") Then End ` Terminates the application End If ` Cancel was not pressed, so convert Age to integer ` The Val() function converts strings to integers intAge = Val(strAge) ` Loop if the age is not in the correct range Do While ((intAge < 10) Or (intAge > 99)) ` The user's age is out of range intPress = MsgBox("Your age must be between " & _ "10 and 99", vbExclamation, "Error!") strAge = InputBox("How old are you?", "Age Ask") ` Check for the Cancel command button If (strAge = "") Then End ` Terminate the program End If intAge = Val(strAge Loop
Figure 8.1 shows the message box error Listing 8.1 displays if the user enters an age value that's less than 10 or more than 99. Listing 8.1 does nothing with MsgBox()'s return value stored in intPress. The user simply presses Enter to close the message box so a check for intPress's value would not help this particular section of code.
NOTE: Listing 8.1 uses the built-in Val() function. Val() accepts a string argument and converts that string to a number (assuming that the string holds the correct digits for a number). The InputBox() function returns a string so the value the user enters into the input box must convert to an integer before you store the value in the integer variable named intAge.
8.1. The user sees this message box as
long as the age is out of range.
The code contains some redundancy. For example, two lines 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 lesson; 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 8.1 is that the body of the loop provides a way for comparison test to terminate. The code contains an intAge 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 comparison values, the comparison 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 comparison test variable, the loop would continue forever.
Visual Basic supports several kinds of loops, and you can use the one that best matches your application's requirements. Whereas the Do While loop continues executing the body of the loop as long as the comparison test is true, the Do Until loop executes the body of the loop as long as the comparison test is false. The program's logic at the time of the loop determines which kind of loop works best in a given situation.
Do Until works almost exactly like the Do While loop except that the Do Until loop continues executing the body of the loop until the comparison 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 (comparison test) Block of one or more Visual Basic statements Loop
TIP: Remember that the comparison test must be false for the loop to continue.
You can use the Do While or the Do Until for almost any loop. Listing 8.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, comparison test for the Do Until is the opposite of that used in Listing 8.1's Do While loop.
Use the loop that makes for the cleanest and clearest comparison test. Sometimes, the logic makes the Do While clearer, whereas other loops seem to work better when you set them up with Do Until. Do Until continues executing a block of Visual Basic statements as long as comparison test is false. As soon as comparison 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.
Dim strAge As String Dim intAge As Integer Dim intPress As Integer ` Get the age in a string variable strAge = InputBox("How old are you?", "Age Ask") ` Check for the Cancel command button If (strAge = "") Then End ` Terminate the program End If ` Cancel was not pressed, so convert Age to integer intAge = Val(strAge) ` Loop if the age is not in the correct range Do Until ((intAge >= 10) And (intAge <= 99)) ` The user's age is out of range intPress = MsgBox("Your age must be " & _ "between 10 and 99", vbExclamation, "Error!") strAge = InputBox("How old are you?", "Age Ask") ` Check for the Cancel command button If (strAge = "") Then End ` Terminate the program End If intAge = Val(strAge) Loop
The 16th line is the only line that marks the difference between Listing 8.1 and Listing 8.2. The age must now fall within the valid range for the loop to terminate.
NOTE: There is really no technical advantage to using Do While or Do Until. Use whichever one seems to flow the best for any given application.
Another pair of Do loops works almost exactly like the two previous loops. Do-Loop While and Do-Loop Until look very much like their counterparts that you learned earlier. But these new loop formats check their comparison 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 Do-Loop While:
Do Block of one or more Visual Basic statements Loop Until (comparison test)
TIP: The hyphen in Do-Loop While serves to remind you that the body of the loop comes before the Loop While statement. The hyphen in the Do-Loop Until performs the same purpose. Some books use ellipses in place of the hyphen, so you may see the statement written as Do...Loop Until.
That Do looks lonely by itself, doesn't it? The purpose of the Do is to signal the beginning of the loop. The loop continues until the Loop Until statement. The comparison 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 comparison 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.
Notice that the Do-Loop While loop's comparison 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 comparison 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 comparison test at the bottom of the loop. Therefore, the body of the loop executes at least once no matter what comparison test turns out to be. The loop continues as long as the comparison test result stays false.
Listing 8.3 contains the age-checking event procedure that's much shorter than the previous versions. comparison test appears at the bottom of the loop, so the extra InputBox() function call is not needed.
Dim strAge As String Dim intAge As Integer Dim intPress As Integer Do strAge = InputBox("How old are you?", "Age Ask") ` Check for the Cancel command button If (strAge = "") Then End ` Terminate program End If intAge = Val(strAge) If ((intAge < 10) Or (intAge > 99)) Then ` The user's age is out of range intPress = MsgBox("Your age must be between " & _ "10 and 99", vbExclamation, "Error!") End If Loop While ((intAge < 10) Or (intAge > 99))
The loop begins almost immediately. The loop's body will always execute at least once, so 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 8.1 and 8.2).
NOTE: In this simple application of the looping statements that you've seen here, the Do-Loop While loop required less code than the Do While and Do Until loops. By changing the Do-Loop While's comparison test, a Do Until would also work. These last two loops will not, in every case, produce less code as they do here. The logic of the application determines which loop works best.
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 that of 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 block 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
A simple example will help demonstrate how the For loop works. The loop in Listing 8.4 computes the total of the numbers from 1 to 10.
intSum = 0 For intNumber = 1 To 10 intSum = intSum + intNumber
Next intNumber intNumber is the CounterVar in the For's format. The CounterVar must be a variable and not a control or a literal. 1 is the For loop's StartVal. The StartVal can be either a number, an expression, or a variable. 10 is the EndVal. EndVal can be either a number, an expression, or a variable. There is no Step specified here. In the For statement's format, the Step IncrementVal is optional (as you can tell from the format's square brackets). If you don't specify a Step value, Visual Basic assumes a Step value of 1. Therefore, both of the following For statements do exactly the same thing:
For intNumber = 1 To 10 For intNumber = 1 To 10 Step 1
Listing 8.4's summing For loop initially assigns to the CounterVar the StartVal in the second line. Therefore, intNumber is assigned 1 at the top of the loop. Visual Basic then executes the body of the loop using the value 1 for intNumber. With intNumber being equal to 1, the third line works as follows the first time through the loop:
intSum = intSum + 1
When Visual Basic executes the Next intNumber statement, Visual Basic returns to the top of the loop (the For statement), adds the Step value 1 to intNumber, and continues the loop again using 2 as intNumber in the loop's body. Therefore, the second time through the loop, the third line becomes this:
intSum = intSum + 2
The loop continues, adding the default Step value 1 to intNumber each time the loop executes. When intNumber becomes 10 (the format's 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 a For statement to sum the values 1 through 10. You could code one long assignment statement like this:
intSum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
You could also code back-to-back assignment statements like this:
IntSum = IntSum + 1 IntSum = IntSum + 2 IntSum = IntSum + 3 IntSum = IntSum + 4 IntSum = IntSum + 5 IntSum = IntSum + 6 IntSum = IntSum + 7 IntSum = IntSum + 8 IntSum = IntSum + 9 IntSum = IntSum + 10
Neither of these approaches is extremely difficult, but what if you needed to add together the first 100 integer numbers? The previous assignments could become tedious indeed, but for the For loop to add the first 100 integers is just as easy to code as for the first 10 integers, as Listing 8.5 demonstrates.
IntSum = 0 For intNumber = 1 To 100 ` Only this line changes IntSum = IntSum + Number Next intNumber
The following loop displays five message boxes:
For intCtr = 1 To 20 Step 4 intPress = MsgBox("This is a message box") Next intCtr
The loop counts up from 1 to 20 by 4s, putting each count into the counter variable named intCtr and printing a message box each time. The Step value changes how Visual Basic updates the CounterVar each time the loop iterates.
New Term: An iteration is one complete cycle through a loop.
If you specify a negative Step value, Visual Basic counts down. The following loop rings the PC's speaker five times:
For intCtr = 5 To 1 Step -1 Beep Next intCtr
NOTE: The Beep statement simply buzzes the speaker on your computer.
WARNING: If you specify a negative Step value, EndVal must be less than StartVal or Visual Basic will execute the loop only once.
Listing 8.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 cmdIntr. 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 8.6 uses five compound cycles.
Sub cmdIntr_Click () ` Use a For loop to calculate a final total ` investment using compound interest. ` ` intNum is a loop control variable ` sngIRate is the annual interest rate ` intTerm is the Number of years in the investment ` curInitInv is the investor's initial investment ` sngInterest is the total interest paid Dim sngIRate As Single, sngInterest As Single Dim intTerm As Integer, intNum As Integer Dim curInitInv As Currency sngIRate = .08 intTerm = 5 ` Watch out... The Code window might convert the ` following literals, 1000.00 and 1.0, to double- ` precision literals with the suffix # to ensure ` accuracy. curInitInv = 1000.00 sngInterest = 1.0 ` Begin at one for first compound ` Use loop to calculate total compound amount For intNum = 1 To intTerm sngInterest = sngInterest * (1 + sngIRate) Next intNum ` Now we have total interest, ` calculate the total investment ` at the end of N years lblFinalInv.Caption = curInitInv * sngInterest End Sub
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. The code's 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, the variables are initialized with start-up values. If you use this event procedure, be sure to add a label named lblFinalInv to a form and add a command button named cmdInt to the form. The middle lines will seem to give you trouble as you type them unless you remember the description you got in Hour 5, "Putting Code into Visual Basic," 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! In addition, Visual Basic converts the 1.0 to 1# on the next line. Don't worry about Visual Basic's pickiness here.
The most important part of this program is the For loop that iterates through each interest rate period (five of them) and compounds the interest on top of the investment to date. Again, don't let the financial part worry you. The calculation is less important than understanding the looping process. After the loop finishes, the event procedure places the compounded investment in the label's Caption property.
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 10 divisions inside a For loop that iterates 10 times. However, the user can enter 0 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 comparison 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 intDivisions = 1 To 10 ` Code to get a sales value If (cngSales <= 0.0) Then Exit For ` Quit the loop early End If ` Process the rest of the code Next intDivisions
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. Visual Basic also supports the Exit Sub statement that terminates a procedure early.
In this hour you have learned how you can add loops to your programs. Computers do not get bored. Your program will execute the same series of instructions over and over until you terminate the loop. Visual Basic supports several forms of looping statements. The Do and For loops provide you with the power to write any kind of looping section your program needs. The choice of loop you use is up to your style and coding preference more than anything else.
The next hour moves away from the theory you've been getting in the last few lessons to get you back to the keyboard and freshen up your application design and construction skills.
The quiz questions and exercises are provided for your further understanding. See Appendix C, "Answers," for answers.
intI = 10 do While intI >= 1 intI = intI - 1 Loop