|
|
|
In the last article, we studied the branching control statements. Today, we take a look at a very important concept of any programming language. Though the syntax will be limited to VB, the idea is common to all languages. We will be discussing looping structures today. Repeating Structures (or Loops)The easiest way to understand repetition is with the aid of a practical example. Consider the steps a milkman performs has he delivers pints of milk to all the houses in a street. There are four basic steps: 1) check number of pints requested on customer's note, 2) fetch required pints from milk float, 3) carry back empties, and 4) move to next house in street. If the street has 20 houses then the milkman has to carry out 80 individual steps to deliver all the milk. A computer simulation of this could be written in Visual Basic using 80 lines of code, one line for each step. However, this is very inefficient. A much better way is to 'wrap' the four basic steps in some kind of repeating structure. Visual Basic supports the following types:
Using Do...Loop StatementsA Do...Loop is a conditional loop, which is active as long or until a condition exists. The key feature of a conditional loop is, of course, the condition (any expression that can return a True or False value). This True/False can be a return value from a function; the value of a property, such as the Value property of an OptionButton; or an expression, such as NumVal < 15. The two basic types of conditional loops are Do...While, which repeats while the condition is True, and Do...Until, which repeats until the condition is True. Using Do...While LoopsA Do...While loop works pretty much as the name implies--it does something while a certain condition is true. For example, to keep adding ten to Num while Num is less than 50, you would use this: Do While Num <50 Num = Num + 10 LoopThe 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 out of the loop and onto the next statement after the Loop statement. The syntax for a Do...While loop is Do While condition statement(s) Loop One point to be taken care in case of Do..While is that the enclosed statements are executed at least once, irrespective of the condition. This is Go To Page: 1 2
The copyright of the article Looping Structures I in Learning Visual Basic is owned by . Permission to republish Looping Structures I in print or online must be granted by the author in writing.
|
|
|
|
|
|
|
|