Page 156 - Open Soource Technologies 304.indd
P. 156
Event Driven Programming
Comments
1. For and Next statements must be paired. If one is missing, the automatic syntax checker
will complain with a wavy underline and a message such as “A ‘For’ must be paired with
a ‘Next’.”
2. Consider a loop beginning with For i = m To n Step s. The loop will be executed exactly
once if m equals n no matter what value s has. The loop will not be executed at all if m
is greater than n and s is positive, or if m is less than n and s is negative.
3. The value of the control variable should not be altered within the body of the loop; doing
so might cause the loop to repeat indefinitely or have an unpredictable number of repeti-
tions.
4. Non integer step values can lead to round off errors with the result that the loop is not
executed the intended number of times. For instance, a loop beginning with For i As
Double = 1 To 2 Step .1 will be executed only 10 times instead of the intended
11 times. It should be replaced with For i As Double = 1 To 2.01 Step .1.
5. Visual Basic provides a way to skip an iteration in a For ... Next loop. When the statement
Continue For is encountered in the body of the loop, execution immediately jumps to
the Next statement. An analogous statement Continue Do is available for Do loops. This
feature is new in Visual Basic 2005.
6. Visual Basic provides a way to back out of a For ... Next loop. When the statement
Exit For is encountered in the body of the loop, execution jumps immediately to the
statement following the Next statement. An analogous statement Exit Do is available for
Do loops.
6.6 Select Case Blocks
A Select Case block is an efficient decision-making structure that simplifies choosing among
several actions. It avoids complex If constructs. If blocks make decisions based on the truth value
of a condition; Select Case choices are determined by the value of an expression called a selector.
Each of the possible actions is preceded by a clause of the form.
case valueList
where valueList itemizes the values of the selector for which the action should be taken.
We can use multiple expressions or ranges in each Case clause.
1: The following program converts the finishing position in a horse race into
a descriptive phrase. After the variable position is assigned a value from
txtPosition, Visual Basic searches for the first Case clause whose value list
contains that value and executes the succeeding statement. If the value of
position is greater than 5, then the statement following Case Else is executed.
150 LOVELY PROFESSIONAL UNIVERSITY