06Control flow
Generic loops
A loop with its own counter, a test, and an update step.
A generic loop gathers the three parts most loops share in one place: a variable that
belongs to the loop, the test, and the update to run after each round. Other languages
call this a for loop.
Expected output
၀
၁၀
၂၀
၃၀
၄၀
The first line starts like a declaration. ဖြစ်ကာ ("being
... and") takes the place of ဖြစ်ပါစေ and turns it into a loop.
| Part | Zaka | Runs |
|---|---|---|
| setup | ကိန်းရှင် ကိန်း သည် ကိန်းပြည့် ဖြစ်၍ တန်ဖိုးသည် ၀ ဖြစ်ကာ | once, before the loop |
| test | ကိန်း သည် ၅ အောက် ငယ်နေသရွေ့ | before each round |
| inner part | the statements in the block | each round |
| update | ပြီးလျှင် ... ("when done, ...") | after each round |
ဖြစ်ပြီး works in place of ဖြစ်ကာ, and the setup can use the short
form of a declaration:
ကိန်းရှင် ကိန်း သည် ကိန်းပြည့် ၀ ဖြစ်ပြီး ....
The update must be the last statement in the block. It is optional; without it, the loop is a while loop with its own variable.
Other updates, other kinds
The update can be whatever statement fits, not just "add one". Here the counter doubles, and it is an 8-bit unsigned integer:
Expected output
၁
၂
၄
၈
၁၆
၃၂
၆၄
The variable belongs to the loop
The loop's variable does not exist outside the loop:
Expected error
error[ZK0301]: "ကိန်း" is not declared
The update goes last
Expected error
error[ZK0213]: the "ပြီးလျှင်" update must be the last statement of the loop
Which loop should I use?
| Situation | Loop |
|---|---|
| each number in a range | counted loop |
| until something happens | while loop |
| a counter that changes in an unusual pattern | generic loop |
Hands on
- Print 100, 90, 80, ... 0 with a generic loop.
- Print the powers of 3 below 1000.
Next: Break and continue.