Loops
for-in iterates over arrays, for-range iterates over number sequences, while loops until a condition is false. break exits early, continue skips to the next iteration.
for..in iterates over arrays.
|
fn main() {
for fruit in ["apple", "banana", "cherry"] {
println(fruit)
}
|
for..in range iterates over numbers. range(n) counts from 0 to n-1.
|
mut sum = 0
for i in range(5) {
sum += i
}
println(sum)
|
range(start, end) and range(start, end, step). |
for i in range(2, 10, 3) {
print("{i} ")
}
println("")
|
while loops until the condition is false.
|
mut n = 1
while n < 100 {
n = n * 2
}
println(n)
|
break exits the innermost loop.
|
for i in range(10) {
if i == 5 { break }
print("{i} ")
}
println("")
|
continue skips to the next iteration.
|
mut evens = []
for i in range(10) {
if i % 2 != 0 { continue }
push(evens, i)
}
println(evens)
|
break and continue work together.
|
mut result = []
for x in [1, 2, 3, 4, 5, 6, 7, 8] {
if x == 7 { break }
if x % 2 == 0 { continue }
push(result, x)
}
println(result)
}
|
|
$ pyr run loops.pyr
apple
banana
cherry
10
2 5 8
128
0 1 2 3 4
[0, 2, 4, 6, 8]
[1, 3, 5]
|