Skip to content
Kavachकवच

For Loop

Also known as: for each foreach iterate iteration loop range step counter index enumerate array traversal

● Beginner5 minBefore this: Variables, OperatorsSpec 4.4

A for loop runs a block of code once for each item: each item of a list, each number of a range, each entry of a map.

Use for when you know what you are going through. When you don't know how many rounds you need, use a while loop instead.

Syntax

for item in things {
    // runs once for each item
}
syntax: Kavach code

Example

Each round, name holds the next item of the list:

fn main() {
    const names = ["Asha", "Ravi", "Meena"]
    for name in names {
        print("Hello, {name}")
    }
}

The program ran and printed:

kavach run list.kav

Hello, AshaHello, RaviHello, Meena
list.kav: Kavach code, then what running it prints

There is no counter to set up, test or increase, so there is no counter to get wrong.

One page for each form

Try it yourself

Print the numbers 1 to 10, one per line.
Show the answer
fn main() {
    for i in 1..=10 {
        print(i)
    }
}

The program ran and printed:

kavach run one-to-ten.kav

12345678910
one-to-ten.kav: Kavach code, then what running it prints

1..=10 includes the 10. With 1..10 the loop would stop at 9.

Go deeper the why, for readers who want it

No C-style loop. Kavach has no for (i = 0; i < n; i++). A range says the same thing with no condition to mistype and no step to forget, and when you need the position as well, enumerate() gives it.

Big loops run on every core. The compiler asks of each counted loop: could the rounds run in any order and give the same answer? This one qualifies, because the compiler proves the sum taken % 1_000_007 once is the same number:

fn main() {
    let total = 0
    for i in 0..100_000 {
        total = (total + i * 7 % 13) % 1_000_007
    }
    print(total)
}

The program ran and printed:

kavach run modular.kav

599992
modular.kav: Kavach code, then what running it prints

Such a loop is cut into chunks and spread over a pool of worker threads. If any check fails in a chunk, the chunks' work is thrown away and the plain loop runs again on one core, so an overflow stops the program at exactly the round, message and line the simple loop would give.

The same loop with 500 million rounds, whole program:

loop — 500M rounds of modular arithmetic · WSL Ubuntu 24.04 · i7-13700HX · kavach build (LLVM) · g++ 13 -O2 · Go 1.23 · .NET 8 (C# start-up included) · best of 9

Kavach60 ms · finished 1st
C++ -O21,361 ms · 23× behind
Go1,377 ms · 23× behind
C#1,561 ms · 26× behind
Verify itgit clone https://github.com/Mithlesh04/kavach && cd kavach sh scripts/run-benchmarks.sh "" benchmarks/loops

Check yourself

QUIZ 1 / 2pick one
What does for i in 1..4 { print(i) } print?