LEARN VOID / 05

Control flow

Follow the logic.

Conditions, loops and explicit exits.

loops.voidDownload source ↓
# Add the odd numbers from 1 through the limit.
func entry(limit: i32) -> i32:
    var total = 0
    var number = 1
    for number <= limit:
        total += number
        number += 2
    return total
Input 5Expected result 9

Repeat while a condition holds

for number <= limit: runs while its condition is true. The loop starts at one and adds two each time, visiting only odd numbers.

Accumulate a result

Each iteration adds the current odd number to total. With a limit of 5, the loop visits 1, 3 and 5, returning 9. A limit below one returns zero without entering the loop.

Use the same keyword for other loops

for item in items: iterates over a collection, and a bare for: repeats until the body exits. break ends a loop; continue moves to its next iteration. The collections guide shows iteration through a list.