06Control flow
If and else
Run statements when a condition is true.
An if statement runs its inner part when a condition is true, and skips it otherwise.
In Zaka: "if condition, then do this": အကယ်၍ <condition> လျှင် <action>.
Expected output
ကလေး
| Zaka | Reads as |
|---|---|
အကယ်၍ | "if" |
လျှင် | "then"; joined to the condition's last verb (ငယ်လျှင်) |
ဖြစ်လျှင် | "if so, then"; a separate word, used after a variable or a full sentence |
ထိုသို့မဟုတ်ဘဲ | "if not so, but"; else if |
သို့မဟုတ်ပါက | "otherwise"; else |
The condition must be a boolean: a comparison, a logical
expression, or a boolean variable. With a boolean variable, use ဖြစ်လျှင်:
အကယ်၍ အောင် ဖြစ်လျှင် ....
Otherwise
သို့မဟုတ်ပါက ("otherwise") names what to run when the condition is false:
Expected output
ကျပါသည်
More than two choices
ထိုသို့မဟုတ်ဘဲ ("if not so, but ...") adds another condition. Zaka tests the conditions
from top to bottom and runs the first branch whose condition is true:
Expected output
အဆင့် ခ
73 is also at least 40, but Zaka stops at the first branch that matches.
Branches with several statements
To run several statements, make the branch a block:
Expected output
မကိန်း
၃၇
စုံကိန်း is "even number" and မကိန်း is "odd number".
An if inside an if
A one-statement branch cannot be another if. That would make it unclear which if an
otherwise belongs to:
Expected error
error[ZK0215]: a single-statement block cannot be another conditional
Put the inner if in a block instead:
Expected output
အောင်
ဂုဏ်ထူး
Hands on
- Print whether a number is positive, negative, or zero.
- Print
"FizzBuzz"if 15 divides a number,"Fizz"if 3 divides it,"Buzz"if 5 does, and the number itself otherwise. Check 9, 10, 15 and 7. Does the order of the tests matter?
Next: While loops.