What is a loop? You've heard the term loop before, but you may not really be sure what it is. A loop is a series of commands that will continue to repeat over and over again untill a condition is met. For example, let's say you have the names of people in an array, and you wanted print a list of all of the names. You could setup a loop that would print the first persons name, and then move on to the next and print her name, etc (the continuing to repeat itself part.) The condition would be that it stops once all of the names have been used.
Types of Loop:
The Do While Loops
The For Loop
The Do Until Loop
The Do While Loop 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 controlling the one-time execution of a single block of code, however, the comparison expression controls the looping statements.
Here is the format of the Do While loop:
Code:
Do While (example)
'Statement
Loop
This loop will continue till example is true.The statement keeps repeating as long as the Do While loop's examples continues to stay true.If it gets false the loop will stop,if the example will not get false,the loop will get infinite and it won't let you get out of the program.
The For Loop I'm not getting into detail because this is the hardest and tricky to use.The For loop also creates a loop. Unlike the Do loops, however, the For loop repeats for a specified number of times.
Format:
Code:
For CounterVar = StartVal To EndVal [Step IncrementVal]
'Statement
Next CounterVar
The Do Until Loop 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 Do Until:
Code:
Do Until (example)
'statement
Loop
Remember that the example must be false for the loop to continue.