စံကား

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.

PartZakaRuns
setupကိန်းရှင် ကိန်း သည် ကိန်းပြည့် ဖြစ်၍ တန်ဖိုးသည် ၀ ဖြစ်ကာonce, before the loop
testကိန်း သည် ၅ အောက် ငယ်နေသရွေ့before each round
inner partthe statements in the blockeach 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:

စံကားZK0301

Expected error

error[ZK0301]: "ကိန်း" is not declared

The update goes last

စံကားZK0213

Expected error

error[ZK0213]: the "ပြီးလျှင်" update must be the last statement of the loop

Which loop should I use?

SituationLoop
each number in a rangecounted loop
until something happenswhile loop
a counter that changes in an unusual patterngeneric loop

Hands on

  • Print 100, 90, 80, ... 0 with a generic loop.
  • Print the powers of 3 below 1000.

Next: Break and continue.