Skip to content
Kavachकवच

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
}
syntax: Kavach code

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
while.kav: Kavach code, then what running it prints

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:

terminal
kavach check src/main.kav
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 errors

Here 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

Start at 1 and keep doubling. Print the first number above 100.
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

128
endless.kav: Kavach code, then what running it prints

Check yourself

QUIZ 1 / 1type what it prints
What is the last line this prints?
let fuel = 3
while fuel > 0 {
    print("burn {fuel}")
    fuel -= 1
}
print("empty")