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.

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;
}
All lessons
Module 1 · A spec file
What a .t27 file holds: a module line, prose lines and comments.
Module 2 · Values and types
Constants, the width of a whole number, and true, false and text.
Module 3 · Arrays, trits and expressions
Lists of values, the three values of a trit, and what operators compute.
Module 4 · Tests and functions
A test block, several small tests in one spec, and a function with typed inputs.
Module 5 · Inside a function
Names with let and var, choices with if and switch, and loops.
Module 6 · Visibility and your own types
What pub shares with other modules, and the structs and enums you declare.
Module 7 · Modules, rules and gen-ts
Reading another module, stating a rule that always holds, and a spec turned into TypeScript.
Module 8 · The compiler and tri
The backends t27c writes, the stages it reads a spec in, and the tri command.
Module 9 · Errors, a program, what next
Reading a compiler error, one small complete program, and the course to take next.