Skip to content

Break and Continue

Control loop execution with break and continue statements.

Break

The break statement exits the loop immediately.

// Stop at 5
for i in 0..10 {
    if i == 5 {
        break;
    }
    print i;
}
// Output: 0, 1, 2, 3, 4

Search Example

let numbers = [10, 20, 30, 40, 50];
let target = 30;

for i in 0..len(numbers) {
    if numbers[i] == target {
        print "Found #{target} at index #{i}";
        break;  // Stop searching
    }
}

While Loop with Break

let count = 0;

while true {
    print count;
    count = count + 1;

    if count >= 5 {
        break;
    }
}

Continue

The continue statement skips to the next iteration.

// Print odd numbers only
for i in 0..10 {
    if i % 2 == 0 {
        continue;  // Skip even numbers
    }
    print i;
}
// Output: 1, 3, 5, 7, 9

Filtering Example

let numbers = [1, -2, 3, -4, 5, -6];

print "Positive numbers:";
for i in 0..len(numbers) {
    if numbers[i] < 0 {
        continue;  // Skip negative
    }
    print numbers[i];
}

Nested Loops

Break in Nested Loops

Break only exits the innermost loop:

for i in 0..3 {
    print "Outer: #{i}";

    for j in 0..5 {
        if j == 2 {
            break;  // Only breaks inner loop
        }
        print "  Inner: #{j}";
    }
}

Continue in Nested Loops

for i in 0..5 {
    if i == 2 {
        continue;  // Skip when i is 2
    }

    for j in 0..3 {
        print "#{i}, #{j}";
    }
}

Common Patterns

Early Exit

let found = false;

for i in 0..1000 {
    if expensive_check(i) {
        found = true;
        break;  // Don't waste time checking rest
    }
}

Skip Invalid Data

let data = [10, 0, 20, 0, 30];

for i in 0..len(data) {
    if data[i] == 0 {
        continue;  // Skip zeros
    }

    let result = 100 / data[i];
    print result;
}

Limited Iterations

let count = 0;
let MAX_ATTEMPTS = 5;

while true {
    let success = try_operation();
    count = count + 1;

    if success == true {
        break;  // Success, exit
    }

    if count >= MAX_ATTEMPTS {
        print "Max attempts reached";
        break;
    }
}

Best Practices

  1. Use break for early exit

    // Don't check all if found
    for i in 0..len(items) {
        if items[i] == target {
            break;
        }
    }
    

  2. Use continue for filtering

    for i in 0..len(data) {
        if !is_valid(data[i]) {
            continue;
        }
        process(data[i]);
    }
    

  3. Avoid deep nesting

    // Use continue to reduce nesting
    for i in 0..len(items) {
        if !condition {
            continue;
        }
        // Process item
    }