Working with Loops

function OpenWin(url, w, h) { if(!w) w = 400; if(!h) h = 300; window.open(url, "_new", "width=" + w + ",height=" + h + ",menubar=no,toobar=no,scrollbars=yes", true); } function Print() { window.focus(); if(window.print) { window.print(); window.setTimeout('window.close();',5000); } }
Team-Fly    

Special Edition Using Microsoft® Visual Basic® .NET
By Brian Siler, Jeff Spotts
Table of Contents
Chapter 7.  Controlling the Flow of Your Program


The other major type of control statement is the loop. You use loops to perform repetitive tasks in your program. Each time the task repeats, the loop is said to have completed an iteration. The three main types of loops are supported by Visual Basic: counter loops, conditional loops, and enumerator loops. Counter, or For, loops perform a task a set number of times. Conditional, or Do, loops perform a task while a specified condition exists or until a specified condition exists. Enumerator loops are used to perform an action on each item in a group of objects. Each of these types of loops is discussed in the following sections.

For Loops

A counter loop also is known as a For loop, or a For/Next loop, because the ends of the loop are defined by the For statement and the Next statement. At the beginning of a For loop, you define a counter variable, as well as the beginning and end points of the variable's value, and optionally the Step value, or the amount it is to be increased or decreased after each pass through the loop. The first time the loop is run, the counter variable is set to the value of the beginning point. Then, after each time the program runs through the loop, the value of the counter is incremented by the Step value and checked against the value of the endpoint. If the counter is larger than the end point, the program skips to the first statement following the loop's Next statement.

Caution

Although you can use any numeric variable for the counter, you need to be aware of the limits of variable types. For example, trying to run a loop 40,000 times using a Short variable causes an error during execution because a Short variable has a maximum value of 32,767.


The following code illustrates using a simple For/Next loop to print the numbers 1 through 10 and their squares in the Output window:

 Dim i As Integer, sOutput As String  For i = 1 To 10      sOutput = i & " squared is " & (i * i)      Debug.WriteLine(sOutput)  Next i 

The sample For loop illustrates some interesting points. First, notice that you are free to use the counter variable (i) in other statements such as mathematical equations. Second, notice the For block ends with the counter variable i after the Next keyword. This is entirely optional; you may just use the word Next by itself and the For loop will execute the same way. Including the variable name in the Next statement makes your program easier to read, especially when you are working with nested loops.

Note

If you have not been programming for a while, you may be wondering why people and books use the variable names i and j as loop counters. The answer is that these variables were traditionally used for this purpose and taught to programmers.


You also should be aware that each time the Next statement is executed, the counter variable is incremented regardless of whether the loop is to be executed again. In the previous sample, the loop executes 10 times and only 10 values are printed. However, if you check the value of i after the loop is finished it will be set to 11.

Using For Loops with Arrays

The next example shows the use of a For/Next loop to reset the elements of three variable arrays to zero. Iterative processing allows these few lines of code to take the place of many. Using For/Next loops in conjunction with arrays in this manner is quite common:

 For CurIndex = 0 To 9      MonthSales(CurIndex) = 0      MonthExpenses(CurIndex) = 0      MonthProfit(CurIndex) = 0  Next 

As you can see in this example and in others in the book, arrays and For loops are often used together. A For loop provides an easy way of looking at or processing each element of an array because the counter variable can be used as the array index.

Note

In VB .NET, all array indexes start as zero. It is important to be conscious of this fact when processing arrays in a loop. For example, if your array has 10 elements, their index values will be 0 to 9. Array indexes are discussed in Chapter 6, "Storing Information in Variables."


Caution

It is not good programming practice to reset the value of the counter variable inside a For loop. Doing so can cause an infinite loop.


Exiting a For Loop Early

Typically, you will want a For loop to run through all the values of the counter variable. However, sometimes you might want the loop to terminate early. To do so, simply place an Exit For statement at the point in your loop where you want the loop to stop. The Exit For statement is typically associated with an If statement that determines whether the loop needs to be exited. In the following sample code from a trivia game, the player's score is examined after each question. If the score dips below zero, no more questions are asked.

 For intQuestion = 1 To intMaxQuestions     bCorrect = AskAQuestion()     If bCorrect Then        intScore = intScore + 1     Else        intScore = intScore - 1     End If     If nScore <= 0 Then Exit For  Next intQuestion 

When the loop terminates (either because all questions have been asked or the score drops below zero), program execution will continue at the statement following the Next statement.

Changing the Step Value

By default, a For loop increments the counter by 1 and counts up. However, you can include the optional Step keyword to specify how the counter is incremented. The code is the first example from this section, rewritten to count down instead of up:

 Dim i As Integer, sOutput As String  For i = 10 To 1 Step -1      sOutput = i & " squared is " & (i * i)      Debug.WriteLine(sOutput)  Next i 

The only differences between this example and the earlier one are the reversed start and end values and the addition of the Step value. Normally, if the beginning value of the loop is greater than the ending value, the loop does not execute at all. However, the Step statement makes the loop count backward, so the loop executes until the counter variable is less than the end point.

Do Loops

The key feature of a conditional loop is, of course, the condition. The condition is any expression that can return either a True or a False value. It can be a user-defined function, such as ValidGrade; the value of a property, such as the Checked property of a radio button; or an expression, such as ArrayIndex < 15. The two basic types of conditional loops are the Do While loop, which repeats while the condition is True, and a Do Until loop, which repeats until the condition is True.

Using Do While Statements

The keyword While in the Do While statement tells the program that the loop will be repeated while the condition expression is True. When the condition in a Do While loop becomes false, the program moves on to the next statement after the Loop statement.

You can use two forms of the Do While loop. The difference between the two is the placement of the condition. You can place the condition either at the beginning of the loop or at the end.

The first form of the Do While loop places the condition at the beginning of the loop, as shown in the following example.

 Do While CurrentSpeed <= SpeedLimit     CurrentSpeed = IncreaseSpeed(1)  Loop 

This code repeatedly calls the IncreaseSpeed function while the condition CurrentSpeed <= SpeedLimitis true. By placing the While condition clause in the Do statement, you tell the program that you want to evaluate the condition before you run any statements inside the loop. If the condition is True, the repetitive statements between the Do statement and the Loop statement are run. Then the program returns to the Do statement to evaluate the condition again. As soon as the condition is False, the program moves to the statement following the Loop statement. Both the Do and the Loop statements must be present to use a DO While loop.

With this form of the loop, the statements inside the loop might never be run. If the condition is False before the loop is run the first time, that is, the car is already traveling at or above the speed limit, the program just proceeds to the statements after the loop. However, there may be times when you always want to execute the statements within the loop at least once, regardless of the condition.

To run the Do While loop at least once, you must use the second form of the Do While loop. This form of the loop places the condition in the Loop statement. This placement tells the program that you want the loop to run at least once and then evaluate the condition to determine whether to repeat the loop:

 ' This will execute 10 times  Dim Counter AS Integer = 0  Do        Counter += 1  Loop While Counter < 10 

Be careful when using the loop in such a manner because statements between the Do and Loop statements will be executed without first checking the loop condition. For example, it might be incorrect to assume that there is data in a file or data set. In cases like this, the other form of the Do Loop statement is more appropriate.

Caution

Do not put the While condition clause in both the Do and the Loop statements because doing so causes an error when you try to run your program.


Note

If you are working on code that was developed by someone else, you might find a loop that starts with a While statement and ends with a Wend statement (Wend stands for "While-End," or the End of the While loop). This type of loop, left over from earlier versions of BASIC, works the same as a Do While loop with the While clause in the Do statement. Starting with Visual Basic .NET, the Wendstatement has been replaced with the more descriptive End While statement. However, the Do While type of loop is more flexible.


Using a Do Until Statement

The Do Until loop is basically the same as the Do While loop except that the statements inside a Do Until loop are run only as long as the condition is False. When the condition becomes True, the loop terminates:

 Dim CarStarted As Boolean  Do    CarStarted = ActivateStarter()  Loop Until CarStarted 

As with the Do While loop, the Do Until loop has two forms: one with the condition in the Do statement and one with the condition in the Loop statement. If you place the condition in the Do statement, it is evaluated before the statements in the loop are executed. The following lines of code illustrate a frequent use of the Do Until statement: reading and processing database records.

 Dim cn As New  SqlConnection("server=bserver\NetSDK;uid=sa;pwd=;database=GrocerToGo")  Dim cmd As New SQLCommand("select name from sysobjects", cn)  Dim rdr As SQLDataReader  cmd.Connection.Open()  rdr = cmd.ExecuteReader()  Do Until Not rdr.Read      Debug.WriteLine(rdr.GetString(0))  Loop  cn.Close() 

The sample loop does not execute at all if the Read function of the SQLDataReader object returns False. Otherwise, if no records were available to read, the GetString method would throw an exception. This is an advantage of testing the condition at the beginning of the loop.

For more on databases, p.599

If you place the condition in the Loop statement, the code within the loop will always execute at least once. Consider the following example:

 Dim Sum As Integer = 0  Dim NewInput As Integer = 0  Do    NewInput = Convert.ToInt32(InputBox("Current Sum=" & Sum & " Enter 0 to exit."))    Sum = Sum + NewInput  Loop Until NewInput = 0 

Even though the variable NewInput is initialized to the value 0, the loop executes before the Until condition is encountered. Executing this example causes the input box to be displayed repeatedly until the user enters 0.

Enumeration Loops

Another type of loop supported by Visual Basic is the For Each loop. The For Each loop is considered to be an enumeration loop, because it is used for processing (or enumerating) each member of a set of objects in an array or collection.

One example of a collection is the DataRows collection, which contains the rows in a database table. The following code uses nested For Each loops to print the fields and values of each table row:

 ' Assumes Dataset has been filled  Dim CurrentRow As DataRow  Dim CurrentCol As DataColumn  For Each CurrentRow In DS.Tables(0).Rows     For Each CurrentCol In DS.Tables(0).Columns        debug.Write(CurrentRow(CurrentCol).ToString() & " ")     Next     debug.writeline("")  Next 

The variables CurrentRow and CurrentCol act similar to the counter variable in a For..Next loop in that it contains the current item being processed.

The For Each loop can also be used with an array, as in the following example:

 Dim MyNumber As Integer  Dim MyArray() As Integer = {5, 7, 9, 3, 1, 6, 8}  For Each MyNumber In MyArray     If MyNumber > 5 Then Debug.WriteLine(MyNumber)  Next MyNumber 

The code first creates a variant array containing seven integers and then uses the enumeration loop to list each integer with a value greater than 5.


    Team-Fly    
    Top
     



    Special Edition Using Visual Basic. NET
    Special Edition Using Visual Basic.NET
    ISBN: 078972572X
    EAN: 2147483647
    Year: 2001
    Pages: 198

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net