Tuesday, February 24, 2009

For and Do loops in VB

Common features of all programming languages are:

  • Output
  • Variables
  • Input
  • Repetition
  • Conditional evaluation
  • Functions

Visual Basic manifests all of these. Examples:

  • Output - the caption of a label control is a form of screen output to inform the user
  • Variables - you can declare them (Dim statement), assign values to them (= operator), declare their type (e.g., AS Single clause), and control their scope by placement (in a method, or in the General section of a form's code) or declaration (local/global, private/public, static keywords).
  • Input - text boxes are a form of user input
  • Repetition - loops. There are different kinds. FOR/NEXT, DO/WHILE, DO/UNTIL
  • Conditional evaluation - If then/End If and Select Case statements

Functions - built-in functions (e.g., IsNumeric(), Val(), Format()) or user-defined functions

We are now focusing on repetition.

For...Next loops use a numeric variable as a counter to keep track of the number of times the loop actually needs to run. This variable is called an index. A typical For loop:

Dim Index

For Index = 1 to 3

[ do something ]


This will repeat any code between the For and Next statements three times. The value of variable Index will take the value 1, then 2, then 3 on the first, second, and third iteration of the loop, respectively.

The Do loop is an alternative way to repeat a block of code. The Do/While loop is common, and has this form:


[ do something ]

Loop While [ condition ]

Note the Do loop, unlike the For loop, does not necessarily involve a built-in variable (For can't run without one). A Do loop equivalent to the above For loop is:

Dim Limit As Integer
Limit = 3


[ do something ]

Limit = Limit - 1

Loop While Limit > 0

In both cases, when execution reaches the lower bound in the code (Next or Loop statement), a decision is made whether to repeat again based on a condition (with For, whether the index variable has reached the stated maximum; with Do, or whether the condition coded in the Loop statement remains true). If the decision is yes, the block of code inside the loop is repeated once again. If no, the loop has finished its job and the next statement below the loop gets executed.

Your Title