စံကား

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

ကလေး
ZakaReads 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:

စံကားZK0215

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.