BRANCHING AND LOOPING
3
Visual Basic includes a number of features that allow us to select among alternative pathways,
or to repeat the execution of a particular block of statements. For example, we can choose to
execute one of several different blocks of statements, depending on the value of an
expression. This process is known as selection. Or, we can choose one of two different paths,
depending on the outcome of a logical test (i.e., depending whether a logical expression is
true or false). This process is known as branching.
Many programs require that a group of instructions be executed repeatedly, until some
particular condition has been satisfied. This process is known as looping. Sometimes the
number of passes through the loop will be known in advance (unconditional looping). In other
situations the looping action will continue indefinitely, until some logical condition has been
satisfied (conditional looping).
Relational Operators and Logical Expressions
In order to carry out branching operations in Visual Basic, we must be able to express
conditions of equality and inequality. To do so, we make use of the following relational
operators (also called comparison operators):
Visual Basic
Name Sample Expression Meaning
Comparison Operator
Equal = m = c m is equal to c
m is not equal to
Not Equal <> m <> c
c
m is greater than
Greater than > m > c
c
Less than < m < c m is less than c
Greater than or m is greater than
>= m >= c
equal to or equal to c
Less than or m is less than or
<= m <= c
equal to equal to c
These operators are used to compare numeric quantities (i.e., constants, numeric variables or
numeric expressions) or strings, thus forming logical expressions that are either true or false.
The operands within a logical expression must be of the same type; i.e., both must be numeric
or both must be strings.
In addition to the relational operators, Visual Basic contains several logical operators. They are
And, Or, Xor (exclusive Or), Not, Eqv (equivalent) and Imp (implies). The first three operators
(And, Or and Xor) are used to combine logical expressions, thus forming more complex logical
expressions. And will result in a condition that is true if both expressions are true. Or will
result in a condition that is true if either expression is true, or if they are both true; Xor,
however, will result in a condition that is true only if one of the expressions is true and the
other is false. Not is used to reverse (negate) the value of a logical expression (e.g., from true
to false, or false to true). Eqv will result in a condition that is true if both expressions have the
same logical value (either both true or both false); and Imp will always result in a true
condition unless the first expression is true and the second is false.
Information and Communication Technology Department 23
Palompon Institute of Technology
BRANCHING AND LOOPING
3
Shown below are several logical expressions that make use of logical operators.
X = 27 And Student = “Smith”
Not(Student = “Smith”) Or (Account = “CURRENT”)
(Student = “Smith”) Eqv (Account = “CURRENT”)
(Student = “Smith” Imp (Account = “CURRENT”)
• Truth Table for operator And.
Expression1 Expression2 Expression1 And Expression2 Result
False False False And False False
False True False And True False
True False True And False False
True True True And True True
Using the And operator, the code will execute if both conditions are True, such as this example:
If (UserName = “PIT”) And (Password = “ICT”) Then
Print “Log-In Successful.”
Else
Print “Access Denied.”
End If
• Truth Table for operator Or.
Expression1 Expression2 Expression1 Or Expression2 Result
False False False Or False False
False True False Or True True
True False True Or False True
True True True Or True True
Using the Or operator, the code will execute if either conditions are True, for example:
If (UserName = “PIT”) Or (UserName = “PITICT”) Then
Print “Log-In Successful.”
Else
Print “Access Denied.”
End If
Information and Communication Technology Department 24
Palompon Institute of Technology
BRANCHING AND LOOPING
3
Conditional Statements
BRANCHING WITH THE If-Then BLOCK
An If-Then block is used to execute a single statement or a block of statements on a conditional basis.
The general form of an If-Then block is:
If logical expression Then
. . . . . . . . . .
executable statements
. . . . . . . . . .
End If
The block of statements included between If-Then and End If will be executed if the logical
expression is true. Otherwise, this block of statements will be bypassed, and the statement
following End If will be executed next.
The following If-Then block permits a single group of statements to be executed conditionally.
If income <= 14000 Then
tax = 0.2 * pay
net = pay – tax
End If
The assignment statements will be executed only if the logical expression income <= 14000 is true.
BRANCHING WITH THE If-Then-Else BLOCK
An If-Then-Else block permits one of two different groups of executable statements to be executed,
depending on the outcome of a logical test. Thus, it permits a broader form of branching than is available
with a single If-Then block.
In general terms, an If-Then-Else block is written as
If logical expression Then
. . . . . . . . . .
executable statements
. . . . . . . . . .
Else
. . . . . . . . . .
executable statements
. . . . . . . . . .
End If
If the logical expression is true, the first group of executable statements will be executed. Otherwise, the
second group of executable statements will be executed. Thus, one group of executable statements will
always be executed. Note that If-Then, Else and End If are separate statements that are used
together to create a complete If-Then-Else block.
Information and Communication Technology Department 25
Palompon Institute of Technology
BRANCHING AND LOOPING
3
Consider the following example:
If (status = “single”) Then
tax = 0.2 * pay
Else
tax = 0.14 * pay
End If
If the logical expression status = “single” is true, then the first assignment statement will be
executed. If the logical expression is false, however, the second assignment statement will be executed.
BRANCHING WITH THE If-Then-ElseIf-Else BLOCK
An If-Then-ElseIf block permits one of two or more different groups of executable statements to be
executed. The general form of an If-Then-ElseIf-Else block is
If logical expression 1 Then
. . . . . . . . . .
executable statements
. . . . . . . . . .
ElseIf logical expression 2 Then
. . . . . . . . . .
executable statements
. . . . . . . . . .
ElseIf logical expression 3 Then
. . . . . . . . . .
executable statements
.
.
.
ElseIf logical expression n Then
. . . . . . . . . .
executable statements
. . . . . . . . . .
Else
. . . . . . . . . .
executable statements
. . . . . . . . . .
End If
Consider the following example:
If correctAnswers >= 10 Then
studGrade = “A”
ElseIf correctAnswers >= 8 Then
studGrade = “B“
ElseIf correctAnswers >= 5 Then
studGrade = “C”
Else
studGrade = “D”
End If
If the variable correctAnswer is greater than or equal to 10 then the first assignment statement will be
executed. If it is greater than or equal to 8, the second assignment statement will be executed until it
Information and Communication Technology Department 26
Palompon Institute of Technology
BRANCHING AND LOOPING
3
reaches the last Else where the variable correctAnswer is less than 5, which will execute the last
assignment statement.
BRANCHING WITH Select...Case STRUCTURE
One way to select a block of statements from several competing blocks is to use a series of If-The-Else
or If-Then-ElseIf-Else blocks. This can be tedious, however, if the number of competing blocks is
moderately large. The Select Case structure frequently offers a simpler approach to this type of
situation.
The most common form of the Select Case structure is written in general term as
Select Case expression
Case value1
executable statements
Case value2
executable statements
. . . . .
Case Else
executable statements
End Select
Consider the example below. The program assumes that a string has been assigned to Status. If the
string is Single, Married, or Retired, an appropriate value will be assigned to TaxRate. If any other
string is entered, an invalid message will be displayed.
‘Tax rate computation based upon marital status
Dim Status As String, TaxRate As Single
Select Case Status
Case “SINGLE”
TaxRate = 0.20
Case “MARRIED”
TaxRAte = 0.14
Case “RETIRED”
TaxRate = 0.12
Case Else
Msgbox (“Invalid – Please try again”)
End Select
Another example of Select Case structure is shown below wherein a selection is based upon the value
of a numeric constant.
Dim Flag As Integer, Label As String
Select Case Flag
Case 1, 3, 5
Label = “Odd digit between 1 and 5”
Case 2, 4, 6
Label = “Even digit between 2 and 6”
Case 7 To 9
Label = “Any digit between 7 and 9”
Information and Communication Technology Department 27
Palompon Institute of Technology
BRANCHING AND LOOPING
3
Case Is >= 10
Label = “Too big”
Case Else
Label = “Non-positive number”
End Select
Looping Through Code
LOOPING WITH For–Next
The For-Next structure is a block of statements that is used to carry out a looping operation; that is, to
execute a sequence of statements some predetermined number of times. The structure begins with a For-
To statement and ends with a Next statement. In between are the statements to be executed.
A more general form of the For-Next structure can be written as
For index = value1 To value2 Step value3
. . . . . . . . . .
executable statements
. . . . . . . . . .
Next index
Within the For-To statement, value3 determines the amount by which value1 changes from one pass to the
next. This quantity need not be restricted to an integer, and it can be either positive or negative. If value3 is
negative, then value1 must be greater than value2. note that value3 is understood to equal 1 if it is not
shown explicitly (i.e., if the Step clause is omitted).
Example 1: To display odd numbers from 1 to 40 using For-Next loop.
Dim counter As Integer
counter = 1
For counter = 1 To 40 Step 2
Print counter
Next counter
Example 2: To determine the sum of the first 10 integers (i.e., 1 + 2 + . . . + 10).
Dim Sum As Integer, i As Integer
Sum = 0
For i = 1 To 10
Sum = Sum + i
Next i
Example 3: To display even numbers from 20 to 0 using For-Next loop.
Dim count As Integer
For count = 20 to 0 Step -2
Print count
Next count
Information and Communication Technology Department 28
Palompon Institute of Technology
BRANCHING AND LOOPING
3
Visual Basic also includes an Exit For statement. This statement permits a transfer out of a For-Next
loop if some particular condition is satisfied. For example, we may wish to jump out of a loop if a stopping
condition is detected during the execution of the loop.
The Exit For statement is generally embedded in an If-Then structure that is included within the loop.
When the Exit For statement is encountered during program execution, control is immediately
transferred out of the For-Next loop, to the first executable statement following Next.
Here is an example illustrating the use of a typical Exit For statement.
sum = 0
For i 1 To 10
sum = sum + i
If sum >= 10 Then
Exit For
Next i
This loop is set up to execute 10 times, but the execution will be terminated if the current value of sum
equals or exceeds 10. In this particular case, the execution will terminate within the fourth pass (because
1+2+3+4=10).
LOOPING WITH Do-Loop
Visual Basic also includes Do-Loop structures, which are convenient when the number of passes through
a loop is not known in advance.
A Do-Loop structure always begins with a Do statement and ends with a Loop statement. However, there
are four different ways to write a Do-Loop structure. Two of the forms require that a logical expression
appear in the Do statement (i.e., at the beginning of the block); the other two forms require that the logical
expression appear in the Loop statement (at the end of the block).
The general forms of the Do-Loop structure are shown below.
First form: Second form:
Do While logical expression Do Until logical expression
. . . . . . . . . . . . . . . . . . . .
executable statements executable statements
. . . . . . . . . . . . . . . . . . . .
Loop Loop
Third form: Fourth form:
Do Do
. . . . . . . . . . . . . . . . . . . .
executable statements executable statements
. . . . . . . . . . . . . . . . . . . .
Loop While logical expression Loop Until logical expression
The first form continues to loop as long as the logical expression is true, whereas the second form continues
to loop as long as the logical expression is not true (until the logical expression becomes true). Similarly, the
third form continues to loop as long as the logical expression is true, whereas the fourth form continues to
loop as long as the logical expression is not true.
Information and Communication Technology Department 29
Palompon Institute of Technology
BRANCHING AND LOOPING
3
Example 1: To determine the sum of the first 10 integers using Do-While Loop (first form).
Sum = 0
Count = 1
Do While count <= 10
Sum = Sum + Count
Count = Count + 1
Loop
This structure will result in 10 passes through the loop. Note that Count is assigned a value of 1 before
entering the loop. The value of Count is then incremented by 1 during each pass through the loop. Once
the value of Count exceeds 10, the execution will cease.
Example 2: To determine the sum of the first 10 integers using Do-Loop While (third form).
Sum = 0
Count = 1
Do
Sum = Sum + Count
Count = Count + 1
Loop While Count <= 10
Example 3: Using Do-Until Loop (second form) to determine the sum of the first 10 integers.
Sum = 0
Count = 1
Do Until Count > 10
Sum = Sum + Count
Count = Count + 1
Loop
Example 4: Using Do-Loop Until (fourth form) to determine the sum of the first 10 integers.
Sum = 0
Count = 1
Do
Sum = Sum + Count
Count = Count + 1
Loop Until Count > 10
Control can be transferred out of a Do-Loop block using the Exit Do statement. This statement is
analogous to Exit For, which is used with For-Next blocks. Thus, when an Exit Do statement is
encountered during program execution, control is transferred out of the Do-Loop block to the first
executable statement following Loop.
Here is an example illustrating Exit Do statement.
Sum = 0
Count = 1
Do While Count <= 10
Sum = Sum + Count
If Sum >= 10 Then
Exit Do
Count = Count + 1
Loop
Information and Communication Technology Department 30
Palompon Institute of Technology
BRANCHING AND LOOPING
3
LOOPING WITH While-Wend
Visual Basic supports While-Wend structures in addition to Do-Loop structures. This structure also
permits conditional looping. The structure begins with the While statement (analogous to Do While),
and ends with the Wend statement (analogous to Loop).
The general form of a While-Wend structure is
While logical expression
. . . . . . . . . .
executable statements
. . . . . . . . . .
Wend
Here is a While-Wend loop example that determines the sum of the first 10 integers.
Sum = 0
Count = 1
While Count <= 10
Sum = Sum + Count
Count = Count + 1
Wend
Information and Communication Technology Department 31
Palompon Institute of Technology