19  Control Flow

Control flow is the order in which individual statements, instructions, or function calls of an imperative program are executed or evaluated. The control flow of a program is regulated by control structures. These control structures can be categorized into three main types: sequential, conditional, and loop structures.

19.1 Sequential Structure

...
Start
Statement 1
Statement 2
Statement N
End

19.2 Conditional Structures

19.2.1 If Statement

True
False
True
False
Start
n
n
n Mod 2 = 1?
Odd
n Mod 2 = 0?
Even
End

19.2.2 If Else Statement

True
False
Start
n
n Mod 2 = 1?
Odd
Even
End

19.2.3 If ElseIf Statement

True
False
True
False
True
False
True
False
Start
score
score >= 90?
A
score >= 80?
B
score >= 70?
C
score >= 60?
D
F
End

19.2.4 Select Case Statement

True
False
True
False
True
False
Start

Select Case
Grade

Case A
Excellent!
Case B
Well done!
Case C
Good job.
Case Else
Needs improvement
End

19.3 Loop Structures

19.3.1 Do While Loop

True
False
Start
Initialize
iteration variable
Do While
Condition

Loop Body
Statement 1
Statement 2
...
Statement N
(Update iteration variable)

End

Example:

Dim n as Integer
n = 1
Do While n < 5
    Debug.Print n
    n = n + 1
Loop

19.3.2 Do Until Loop

False
True
Start
Initialize
iteration variable
Do Until
Condition

Loop Body
Statement 1
Statement 2
...
Statement N
(Update iteration variable)

End

Example:

Dim n as Integer
n = 1
Do Until n > 5
    Debug.Print n
    n = n + 1
Loop

19.3.3 Do Loop While

True
False
Start
Initialize
iteration variable
Do

Loop Body
Statement 1
Statement 2
...
Statement N
(Update iteration variable)

While
Condition
End

Example:

Dim n as Integer
n = 1
Do
    Debug.Print n
    n = n + 1
Loop While n <= 5

19.3.4 Do Loop Until

False
True
Start
Initialize
iteration variable
Do

Loop Body
Statement 1
Statement 2
...
Statement N
(Update iteration variable)

Until
Condition
End

Example:

Dim n as Integer
n = 1
Do
    Debug.Print n
    n = n + 1
Loop Until n > 5

19.3.5 For Loop Next

True
False
Start
For
Initialize
iteration variable
Condition

Loop Body
Statement 1
Statement 2
...
Statement N

Update iteration
variable
End

Example:

Dim n as Integer
n = 1
For n = 1 To n <= 5 Step 1
    Debug.Print n
Next n

19.3.6 For Each Next

True
False
Start
Initialize
collection
For Each
Next element
in collection?

Loop Body
Statement 1
Statement 2
...
Statement N

End

Example:

'Creating collection
Dim numbers As Collection
Set numbers = New Collection

'Populating collection
numbers.Add 1
numbers.Add 2
numbers.Add 3
numbers.Add 4
numbers.Add 5

Dim n As Variant
For Each n in numbers
    Debug.Print n
Next n