While Loop
Also known as: while loop repeat until condition endless infinite do while
● Beginner4 minBefore this: For LoopSpec 4.5
A while loop repeats a block as long as its condition is true.
Use while when you don't know in advance how many rounds you need: until the fuel runs out, until the user types "quit". When you are going through things you already have, a for loop is clearer.
Syntax
while condition {
// runs again and again while condition is true
}Example
fn main() {
let fuel = 3
while fuel > 0 {
print("burn {fuel}")
fuel -= 1
}
print("empty")
}The program ran and printed:
kavach run while.kav
burn 3burn 2burn 1empty
The condition is checked before every round. Something in the block must change it, or the loop never stops.
A loop that never ends
When nothing in the loop changes its condition, and nothing leaves it, the compiler warns before the program runs:
warning: this loop never ends: `n` doesn't change in it, and nothing in it leaves it. Change it in the loop, add a `break`, or write `while true` if it should run forever (spec 4.7)
--> src/main.kav:3:11
|
3 | while n < 10 {
| ^^^^^^
src/main.kav: no errorsHere n never changes. Add n += 1 in the loop, or write while true if it really should run forever.
One page for each form
Try it yourself
Show the answer
fn main() {
let n = 1
while true {
n *= 2
if n > 100 {
break
}
}
print(n)
}The program ran and printed:
kavach run endless.kav
128Check yourself
let fuel = 3
while fuel > 0 {
print("burn {fuel}")
fuel -= 1
}
print("empty")