break

In programming languages like X3, the "break" keyword is used within loops (such as "for" and "while" loops) to prematurely exit the loop when a certain condition is met. Here's how you would use the "break" keyword in your X3 language:

Basic Usage with "for" Loop:

# Using 'break' keyword in 'for' loop
for var i = 1 to 5 then
    if i == 3 then
        break  # Exit the loop when i is 3
    end
    show(i)
end

Explanation:

  • In this example, the "for" loop iterates over the values from 1 to 5.

  • When the loop variable i is equal to 3, the "break" keyword is encountered, causing the loop to terminate immediately.

  • As a result, the loop stops executing, and the subsequent iterations are skipped.

Basic Usage with "while" Loop:

var i = 0

# Using 'break' keyword in 'while' loop
while i < 5 then
    i = i + 1
    if i == 3 then
        break  # Exit the loop when i is 3
    end
    show(i)
end

Explanation:

  • In this example, the "while" loop continues to execute as long as the condition i < 5 is true.

  • Within each iteration, the loop variable i is incremented by 1.

  • When i becomes equal to 3, the "break" keyword is encountered, causing the loop to terminate immediately.

  • As a result, the loop stops executing, and the subsequent iterations are skipped.

Usage in Nested Loops:

# Using 'break' keyword in nested loops
for var i = 1 to 3 then
    for var j = 1 to 3 then
        if j == 2 then
            break  # Exit the inner loop when j is 2
        end
        show("({i}, {j})")
    end
end

Explanation:

  • In this example, a nested "for" loop structure is used.

  • When the inner loop variable j is equal to 2, the "break" keyword is encountered, causing the inner loop to terminate immediately.

  • As a result, the inner loop stops executing, and the outer loop continues with its next iteration.

By incorporating the "break" keyword in your X3 language, you provide users with a way to prematurely exit loop constructs based on specific conditions. This capability allows for more flexible control flow within loops and enhances the efficiency of algorithmic implementations in X3 programs.

Last updated