t27.aiРусский

Loops: while and for

You will learn

The three loop forms the compiler accepts and how a range is written.

while (i < n) { i = i + 1; } repeats its block while the condition is true, and the block must move toward making it false. for i in 0..n { } walks i from 0 up to n, with n itself left out. The compiler also accepts the Zig form, for (0..4) |i| { }. A loop usually updates a var declared before it.

Try it

Work out by hand what sum_to returns for n = 4, then write it as a constant with a test.

Open the interactive lesson →

t27 basics 15: three loop forms
t27 basics 15: three loop forms ↗

while, for in a range and the Zig-style for, each checked with the real t27 compiler, and a range drawn step by step. Lesson 15 of the t27 basics course.

specs/basics/15_loops.t27

// SPDX-License-Identifier: Apache-2.0
; t27 basics, lesson 15: Loops: while and for.
; while repeats while a condition holds; for walks a range of numbers.

module basics_15_loops;

pub fn sum_to(n: u8) -> u16 {
    var s : u16 = 0;
    for i in 0..n {
        s = s + i;
    }
    return s;
}

pub fn count_up(n: u8) -> u8 {
    var i : u8 = 0;
    while (i < n) {
        i = i + 1;
    }
    return i;
}

pub const SUM_BELOW_5 : u16 = 10;

test zero_to_four_add_up_to_ten {
    assert SUM_BELOW_5 == 0 + 1 + 2 + 3 + 4;
}

Open the lesson's spec in the player ↗

All lessons