Skip to content

Loops

Loops allow you to repeat code multiple times.

For Loop

For loops iterate over a range of numbers.

Basic For Loop

// Print 0 to 4
for i in 0..5 {
    print i;
}

The range is inclusive of start, exclusive of end: 0..5 means 0, 1, 2, 3, 4.

Iterating Over Arrays

let fruits = ["apple", "banana", "cherry"];

for i in 0..len(fruits) {
    print fruits[i];
}

Counting Examples

// Count from 1 to 10
for i in 1..11 {
    print i;
}

// Even numbers
for i in 0..11 {
    if i % 2 == 0 {
        print i;
    }
}

// Multiplication table
for i in 1..11 {
    let result = i * 5;
    print "5 × #{i} = #{result}";
}

While Loop

While loops repeat as long as a condition is true.

Basic While Loop

let count = 0;

while count < 5 {
    print count;
    count = count + 1;
}

User Input Loop

let running = true;

while running == true {
    let input = input("Enter 'quit' to exit: ");

    if input == "quit" {
        running = false;
    } else {
        print "You entered: #{input}";
    }
}

Sentinel Value Loop

let sum = 0;
let number = 0;

while number != -1 {
    let input = input("Enter number (-1 to stop): ");
    number = int(input);

    if number != -1 {
        sum = sum + number;
    }
}

print "Total: #{sum}";

Nested Loops

Loops inside loops:

// Multiplication table
for i in 1..6 {
    for j in 1..6 {
        let product = i * j;
        print "#{i} × #{j} = #{product}";
    }
    print "";  // Blank line
}

Pattern Printing

// Print a triangle
for i in 1..6 {
    for j in 0..i {
        print "*";
    }
    print "";
}

Common Patterns

Accumulator

let sum = 0;

for i in 1..101 {
    sum = sum + i;
}

print "Sum of 1-100: #{sum}";

Find Maximum

let numbers = [12, 45, 7, 89, 23];
let max = numbers[0];

for i in 1..len(numbers) {
    if numbers[i] > max {
        max = numbers[i];
    }
}

print "Maximum: #{max}";
let items = ["apple", "banana", "cherry"];
let target = "banana";
let found = false;

for i in 0..len(items) {
    if items[i] == target {
        found = true;
        print "Found at index #{i}";
        break;
    }
}

if found == false {
    print "Not found";
}