06Control flow
While loops
Repeat statements as long as a condition holds.
A loop runs its inner part again and again. A while loop keeps going as long as a
condition is true. In Zaka: "as long as condition, do the following":
<condition> နေသရွေ့ <action>.
Expected output
၁
၂
၄
၈
၁၆
၃၂
၆၄
ပြီးပြီ
Each round goes like this:
- Test the condition. If it is false, the loop ends, and the program goes on after it.
- Run the inner part.
- Go back to step 1.
After 64 is printed, the number is doubled to 128. Then the test "128 is less than 100" is false, so the loop ends and 128 is never printed.
| Zaka | Reads as |
|---|---|
နေသရွေ့ | "as long as"; joined to the condition's last verb (ငယ်နေသရွေ့) |
ဖြစ်နေသရွေ့ | "as long as it is so"; a separate word, used after a variable or a full sentence |
One-statement loops
The inner part can be a single statement:
Expected output
၀
A boolean as the condition
Expected output
၈
The loop stops in the round where အကြိမ် * အကြိမ် first reaches 50 or more: 8 × 8 = 64.
Loops that never end
If the condition never becomes false, the loop runs forever. Make sure the inner part
changes something the condition depends on. In the Explorer, press Stop to end a
program that will not stop. In a terminal, press Ctrl+C.
Hands on
- Print the numbers 10 down to 1 with a while loop.
- Starting from 1000, keep halving the number while it is greater than 1. How often does it get halved?
Next: Counted loops.