Lesson 4 — Repeating things
You are here
- Your first program ✓
- Values and variables ✓
- Making decisions ✓
- Repeating things ←
- Functions
- Lists and hashes
- Strings
- Organizing programs
- Classes
What are we learning?
A loop repeats instructions while a condition stays true.
Smallest useful loop: while
echo
i: int = 1;
while i <= 3 {
say(i);
i = i + 1;
}Output
text
1
2
3What happens
- Start with
ias1. - Ask: is
iless than or equal to3? Yes → printi, then add1toi. - Repeat until the answer is no.
Do not forget to change the condition
If you never change i, the loop can run forever. Always move toward finishing the condition.
Counting with for
When you want a range of whole numbers, for is handy:
echo
for n: int in 1..3 {
say(n);
}Output
text
1
2
31..3 means from 1 through 3 (both ends included).
Try it
Change the loop so it prints 1 through 5.
Predict it
echo
i: int = 0;
while i < 2 {
say("hi");
i = i + 1;
}Show answer
text
hi
hiFix it
This never ends (and will hang until stopped):
echo
while true {
say("loop");
}Use a condition that becomes false, like i <= 3, and update i inside the loop.
Deeper (later)
break, continue, foreach, and ... (exclusive ranges) are in Control Flow (full) and Loops Reference.
