DECISION-MAKING (BRANCHING) MECHANISMS

If ... Then ... Else or Elseif ... End If Structures

The Else or the ElseIf parts are actually optional. If they are left out, then we have the If ... Then ... End If structure.

It is used in the following way:

If (LogicalExpression) Then
    statement(s)
End If

where LogicalExpression is a logical expression that evaluates to either True or False, and statement(s) is a single or a group of statements.

If the LogicalExpression evaluates to True, then the statement(s) part is executed, otherwise the statement(s) part is skipped. In either case program control is passed afterwards to the statement immediately following the If ... Then ... End If structure.

For example, if Score is an integer variable and Passing is a boolean variable, then one can write:

Passing = False
If ( Score >= 60 )
    Passing = True
End If

This means that in order to pass the course, a student has to have a score of 60 or higher.

The above code can also be written by using the Else option as:

If ( Score >= 60 )
    Passing = True
Else
    Passing = False
End If

So there are two possible outcomes depending on the value of a certain logical expression.

Multiple (more than two) branches can be obtained by using the ElseIf option a number of times:

If (LogicalExpression1) Then
    statement1
ElseIf (LogicalExpression2) Then
    statement2
ElseIf (LogicalExpression3) Then
    statement3
... etc.
End If

The last ElseIf part can be replaced by Else without an associated logical expression:

If (LogicalExpression1) Then
    statement1
ElseIf (LogicalExpression2) Then
    statement2
... etc.
Else
    defaultStatement
End If

In this case, if none of the logical expression is evaluated to True, then the defaultStatement will be executed.

In all of the above cases, program control is passed afterwards to the statement immediately after the entire If ... structure.

For example, if Grade is a string variable that stores the letter grade for a student in a course, it can be determined by:

If ( Score >= 90 ) Then
    Grade = "A"
ElseIf ( Score >= 80 ) Then
    Grade = "B"
ElseIf ( Score >= 70 ) Then
    Grade = "C"
ElseIf ( Score >= 60 ) Then
    Grade = "D"
Else
    Grade = "F"
End If

The Select Case Statement


The Select Case statement provides an efficient alternative to the series of ElseIf conditionN statements when conditionN is a single expression that can take various values.

You will find a description of its syntax and an example how it can be used on page 266 of our textbook.