if Statement
Syntax
(Single-line form)
"if" ─► Expression ─► "then" ─► CommandStatement ─► EOL(Multi-line form)
"if" ─► Expression ─► "then" ─► EOL ──┐
┌─────────────────────────────────┘
▼
Statements
│◄─────────────────────────────────────────────────────────────┐
├───► "else if" ─► Expression ─► "then" ─► EOL ─► Statements ──┘
│
├───► "else" ─► EOL ─► Statements ──┐
│◄──────────────────────────────────┘
▼
"end if" ─► EOL
Usage
An
if statement is used to make decisions.
It is used in conjunction with
Boolean values which represent the result of a decision as
true or
false.
The "if ... then ..." structure works just how it sounds.
If a given condition is true, then the given statements are executed.
Otherwise the statements are skipped.
Consider the following example.
sub Main()
dim x as Number
input x
if x < 0 then
print "Negative number"
else if x > 0 then
print "Positive number"
else
print "Zero"
end if
end sub
After the user types a number and presses Enter, only one of the three
print statements will execute.
It may help to view the path of execution using a flow chart.
↓
▄▀▄
▄▀ ▀▄ true ▄▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀█▀
█ x<0 █───────► ▄▀ print "Negative number" ▄▀
▀▄ ▄▀ ▄█▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▀
▀▄▀
↓ false
▄▀▄
▄▀ ▀▄ true ▄▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀█▀
█ x>0 █───────► ▄▀ print "Positive number" ▄▀
▀▄ ▄▀ ▄█▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▀
▀▄▀
↓ false
▄▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀█▀
▄▀ print "Zero" ▄▀
▄█▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▀
Single-line form
There is a short form that fits on a single line.
if x = 0 then print "Zero"
This convenience form supports only a single statement.
Multi-line form
The full form is composed of three sections: the
if block, the optional
else if blocks, and the optional
else block.
if <condition> then
<statements>
else if <condition> then
<statements>
else if <condition> then
<statements>
else
<statements>
end if