While Loop, Do While Loop, Do Until Loop, While End While - VB.NET

The Do. . .Loop executes a block of statements for as long as a condition is True, or until a condition becomes True. Visual Basic evaluates an expression (the loop’s condition), and if it’s True, the statements in the loop’s body are executed. The expression is evaluated either at the beginning of the loop (before executing any statements) or at the end of the loop (the block statements are executed at least once). If the expression is False, the program’s execution continues with the statement following the loop.

There are two variations of the Do. . .Loop statement; both use the same basic model. A loop can be executed either while the condition is True or until the condition becomes True. These two variations use the keywords While and Until to specify for how long the statements will be executed. To execute a block of statements while a condition is True, use the following syntax:

Do While condition statement-block LoopCode language: VB.NET (vbnet)

To execute a block of statements until the condition becomes True, use the following syntax:

Do Until condition statement-block LoopCode language: VB.NET (vbnet)

When Visual Basic executes these loops, it first evaluates condition. If condition is False, a Do. . .While loop is skipped (the statements aren’t even executed once), but a Do. . .Until loop is executed. When the Loop statement is reached, Visual Basic evaluates the expression again; it repeats the statement block of the Do. . .While loop if the expression is True or repeats the statements of the Do. . .Until loop if the expression is False. In short, the Do. . .While loop is executed when the condition is True, and the Do. . .Until loop is executed when the condition is False. A last variation of the Do. . .Loop statement allows you to evaluate the condition at the end of the loop. Here’s the syntax of both loops, with the evaluation of the condition at the end of the loop:

Do statement-block Loop While condition Do statement-block Loop Until conditionCode language: VB.NET (vbnet)

As you can guess, the statements in the loop’s body are executed at least once, because no testing takes place as the loop is entered.

Here’s a typical example of using a Do. . .Loop: Suppose that the variable MyText holds some text (like the Text property of a TextBox control), and you want to count the words in the text. (We’ll assume that there are no multiple spaces in the text and that the space character separates successive words.) To locate an instance of a character in a string, use the IndexOf method, which is discussed in detail in Chapter, “‘Handling Strings, Characters, and Dates.” This method accepts two arguments: the starting location of the search and the character being searched. The following loop repeats for as long as there are spaces in the text. Each time the IndexOf method finds another space in the text, it returns the location of the space. When there are no more spaces in the text, the IndexOf method returns the value –1, which signals the end of the loop, as shown:

Dim MyText As String = "The quick brown fox jumped over the lazy dog" Dim position, words As Integer position = 0: words = 0 Do While position >= 0 position = MyText.IndexOf(" ", position + 1) words += 1 Loop MsgBox("There are " & words & " words in the text")Code language: VB.NET (vbnet)

The Do. . .Loop is executed while the IndexOf method function returns a positive number, which means that there are more spaces (and therefore words) in the text. The variable position holds the location of each successive space character in the text. The search for the next space starts at the location of the current space plus 1 (so the program won’t keep finding the same space). For each space found, the program increments the value of the words variable, which holds the total number of words when the loop ends. By the way, there are simpler methods of breaking a string into its constituent words, such as the Split method of the String class, which is discussed in Chapter 13. This is just an example of the Do. . .While loop.

You might notice a problem with the previous code segment: It assumes that the text contains at least one word. You should insert an If statement that detects zero-length strings and doesn’t attempt to count words in them.

You can code the same routine with the Until keyword. In this case, you must continue searching for spaces until position becomes –1. Here’s the same code with a different loop:

Dim position As Integer = 0 Dim words As Integer = 0 Do Until position = -1 position = MyText.IndexOf(" ", position + 1) words = words + 1 Loop MsgBox("There are " & words & " words in the text")Code language: VB.NET (vbnet)

While …End While Loop

The While. . .End While loop executes a block of statements as long as a condition is True. The loop has the following syntax:

While condition statement-block End WhileCode language: VB.NET (vbnet)

If condition is True, all statements in the bock are executed. When the End While statement is reached, control is returned to the While statement, which evaluates condition again. If condition is still True, the process is repeated. If condition is False, the program resumes with the statement following End While.

The loop in Listing 3.5 prompts the user for numeric data. The user can type a negative value to indicate he’s done entering values and terminate the loop. As long as the user enters positive numeric values, the program keeps adding them to the total variable.

Listing 3.5: Reading an Unknown Number of Values

Dim number, total As Double number = 0 While number => 0 total = total + number number = InputBox("Please enter another value") End WhileCode language: VB.NET (vbnet)

I’ve assigned the value 0 to the number variable before the loop starts because this value isn’t negative and doesn’t affect the total.

Sometimes, the condition that determines when the loop will terminate can’t be evaluated at the top of the loop. In these cases, we declare a Boolean value and set it to True or False from within the loop’s body. Here’s the outline of such a loop:

Dim repeatLoop As Boolean repeatLoop = True While repeatLoop { statements } If condition Then repeatLoop = True Else repeattLoop = False End If End WhileCode language: VB.NET (vbnet)

You may also see an odd loop statement like the following one:

While True { statements } End WhileCode language: VB.NET (vbnet)

It’s also common to express the True condition as follows:

While 1 = 1Code language: VB.NET (vbnet)

This seemingly endless loop must be terminated from within its own body with an Exit While statement, which is called when a condition becomes True or False. The following loop terminates when a condition is met in the loop’s body:

While True { statements } If condition Then Exit While { more statements } End WhileCode language: VB.NET (vbnet)

Related lessons:

  1. For Loop – For…Next Statement
  2. vb If Then Statement
  3. If Then Else Statement
  4. Control Flow Statements
  5. Nested Control Structures
  6. Boolean and String Variables

Từ khóa » Visual Basic Do Until Example