3. Decisions and loops¶
So far the program runs every line once, from top to bottom. In this lesson it chooses what to do, and repeats work.
إذا: choosing¶
إذا means «if». What's between { and } is a block, and it only runs when the
condition is true: here, when the temperature is above 30, the program says «it's hot, drink
plenty of water». Add what happens otherwise with وإلا («else»), and ask more than one
question:
ثابت الدرجة = 72
إذا الدرجة >= 90 {
اطبع("ممتاز")
} وإلا إذا الدرجة >= 50 {
اطبع("ناجح")
} وإلا {
اطبع("حاول مرة أخرى")
}
إذا gives a value¶
In Ḍād, إذا returns a value: the last thing in the block it chose. So you can write:
ثابت العمر = 15
ثابت الفئة = إذا العمر < 13 { "طفل" } وإلا إذا العمر < 18 { "مراهق" } وإلا { "بالغ" }
اطبع(الفئة)
Combine conditions with و («and») and أو («or»), and negate them with ليس («not»):
لكل: repeating a known number of times¶
لكل … من … إلى means «for each … from … to». The name ع takes the values 1, then 2… up
to 5. There are other ways to count:
| You write | You get |
|---|---|
من 1 إلى 5 |
1, 2, 3, 4, 5 |
من 0 حتى 5 |
0, 1, 2, 3, 4 (without 5) |
من 0 إلى 10 بخطوة 5 |
0, 5, 10 |
من 3 إلى 1 بخطوة -1 |
3, 2, 1 |
An example: the times table for 7.
7 × 1 = 7
7 × 2 = 14
7 × 3 = 21
7 × 4 = 28
7 × 5 = 35
7 × 6 = 42
7 × 7 = 49
7 × 8 = 56
7 × 9 = 63
7 × 10 = 70
لكل … في («for each … in») goes through the letters of a text too:
طالما: repeating until something happens¶
When you don't know the number of times in advance, use طالما («while»). The block
repeats while the condition is true:
// كم سنة حتى يتضاعف المال بفائدة 10٪؟
متغير المال = 1000.0
متغير السنوات = 0
طالما المال < 2000 {
المال *= 1.1
السنوات += 1
}
اطبع("بعد"، السنوات، "سنوات يصير المال"، المال.تقريب(2))
This asks how many years it takes money to double at 10% interest. تقريب(2) rounds to two
decimal places.
Careful: if the condition stays true forever, the work repeats with no end. Stop the
program with Ctrl+C; in the playground, Ḍād stops it for you and says why.
توقف and تابع¶
توقف («stop») leaves the loop at once, and تابع («continue») skips to the next round:
Exercise¶
- Print the numbers from 1 to 20, but write «فز» instead of each number divisible by 3, «بز» instead of each number divisible by 5, and «فز بز» if it is divisible by both.
- Add up the numbers from 1 to 100 and print the total.
Solution
Next: Functions