Loop Structures

Master for loops, while loops, and iteration patterns

For Loops with Range Operator (~)

Linea v4.1 introduces the ~ range operator for clean, expressive for loops:

Basic Syntax

for i from start~end {
    // loop body
}

Simple Range

Iterate from start to end (inclusive):

for i from 1~5 {
    display i
}
// Output: 1, 2, 3, 4, 5

Range with Step

Use step to skip values:

for i from 0~10 step 2 {
    display i
}
// Output: 0, 2, 4, 6, 8, 10

Reverse Iteration

Use negative step to iterate backwards:

for i from 10~1 step -1 {
    display i
}
// Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

Dynamic Ranges

Use variables for range bounds:

var start @ int = 1
var end @ int = 100
for i from start~end step 5 {
    display i
}

Iterating Over Arrays

With Index

var arr @ [int] = [10, 20, 30, 40]
for i from 0~3 {
    display arr[i]
}

Using Length

var arr @ [int] = [5, 10, 15]
var len @ int = len(arr)
for i from 0~(len-1) {
    display arr[i]
}

Break and Continue

Break

Exit a loop early:

for i from 1~10 {
    if i == 5 {
        break  // Exit loop when i equals 5
    }
    display i
}
// Output: 1, 2, 3, 4

Continue

Skip to next iteration:

for i from 1~10 {
    if i % 2 == 0 {
        continue  // Skip even numbers
    }
    display i
}
// Output: 1, 3, 5, 7, 9

While Loops

Basic While

var count @ int = 0
while count < 5 {
    display count
    count = count + 1
}

While with Break

var x @ int = 0
while true {
    display x
    x = x + 1
    if x > 10 {
        break
    }
}

Nested Loops

Matrix Iteration

var matrix @ [[int]] = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for i from 0~2 {
    for j from 0~2 {
        display matrix[i][j]
    }
}

Common Patterns

Summing Elements

var arr @ [int] = [1, 2, 3, 4, 5]
var sum @ int = 0
for i from 0~4 {
    sum = sum + arr[i]
}
display sum  // Output: 15

Finding Maximum

var arr @ [int] = [3, 7, 2, 9, 1]
var max @ int = arr[0]
for i from 1~4 {
    if arr[i] > max {
        max = arr[i]
    }
}
display max  // Output: 9

Performance Tips