continue/break

This commit is contained in:
allexanderbergmns
2026-08-24 15:41:37 +02:00
parent 18b0b38490
commit 55a3ee0b18
6 changed files with 135 additions and 2 deletions
+23
View File
@@ -65,6 +65,29 @@ fn main() {
println("i is back to ")
println(i) // 100
// break and continue
for i in 0..10 {
if i == 2 {
continue // skip 2
}
if i == 5 {
break // stop at 5
}
print(i)
print(" ")
}
println("")
// find the first even number in an array
let found = -1
for x in a {
if x % 2 == 0 {
found = x
break
}
}
println("first even in a: " + found) // 10
assert sum([1, 2, 3, 4]) == 10
assert len(squares) == 5
assert squares[4] == 16
+47
View File
@@ -78,6 +78,53 @@ fn test_for_in() {
assert squares[3] == 9
}
fn test_break_continue() {
// break exits the loop early
let total = 0
for i in 0..100 {
if i == 5 {
break
}
total = total + i
}
assert total == 10 // 0+1+2+3+4
// continue skips to the next iteration
let sum = 0
for i in 0..6 {
if i == 3 {
continue
}
sum = sum + i
}
assert sum == 12 // 0+1+2+4+5 (3 skipped)
// break and continue in while loops
let n = 0
while true {
n = n + 1
if n == 3 {
continue
}
if n == 5 {
break
}
}
assert n == 5
// continue advances the iterator in for-in loops (no infinite loop)
let odds = []
for x in [1, 2, 3, 4, 5] {
if x % 2 == 0 {
continue
}
push(odds, x)
}
assert odds == odds
assert len(odds) == 3
assert odds[2] == 5
}
fn test_failing() {
// this one is meant to fail — shows up in `vr test` output
assert 1 == 2