Skip to main content

Loops

Loops are control structures that automate the repetition of code blocks. By using loops, you avoid writing the same instructions over and over, improve readability, and handle large or dynamic data sets with ease.

“Imagine asking someone to say ‘Hello’ ten times. Instead of saying it yourself ten times, you could simply ask them to repeat it — that’s what a loop does in code.”


Why Use Loops?

  1. Automation
    Automate repetitive tasks without manual duplication of code.
  2. Scalability
    Process collections or ranges of any size without altering the loop body.
  3. Maintainability
    Encapsulate repetition in a single block, making updates and debugging simpler.

Loop Flow Diagram

Loop Flow Diagram


Loop Overview

S/NLoop TypeDescription
1For LoopIterates a counter over a numeric range with optional step
2Foreach LoopTraverses each element in an array or key/value pair in a dictionary
3Repeat WhilePre-test loop that repeats while a condition remains true
4Repeat TimesExecutes a block a fixed number of times
5Iterate LoopGeneric iteration over a collection with explicit parentheses
6Generate LoopCustom numeric loop defined by start, end, step and terminated by stop

ASCII Diagram – While Decision

+-------------------+
| Start |
+-------------------+
|
v
[Check Condition]
/ \
True False
| |
Action Block End Loop
|
+------+------+
|
End

1. For Loop

A for loop iterates a counter variable over a discrete numeric range. It is ideal when you know in advance how many times to run the loop.

Theory

  • Initialization: Set the counter to a starting value.
  • Condition: Before each iteration, check if the counter is within the range.
  • Body Execution: Run the block of code.
  • Increment: Update the counter (by 1 or a specified step).

Syntax

for i from start to end [step n]
// code using i
end for

Examples

for i from 1 to 5
show(i)
end for

for i from 0 to 10 step 2
show(i)
end for

2. Foreach Loop

A foreach loop traverses each element in a collection—arrays or dictionaries—providing direct access to the item (and key, for dictionaries). It is the most readable way to process every element without managing an index.

Theory

  • Collection Access: The loop internally retrieves each element in order.
  • Element Binding: Binds the current element (and optionally its key) to loop variables.
  • Automatic Termination: Ends when all elements have been processed.

You can also query the length of an array via array.length() if needed inside the loop.

Syntax

foreach element in collection
// code using element
end foreach

foreach key, value in dictionary
// code using key and value
end foreach

Examples

declare fruits[]
set fruits to ["apple", "banana", "cherry"]

foreach fruit in fruits
show(fruit)
end foreach

declare scores
set scores to { "Alice": 90, "Bob": 85 }

foreach name, grade in scores
show(name + " scored " + grade)
end foreach

// Using length() inside a foreach
declare data[]
set data to [10,20,30]

foreach item in data
show(item + " (index < " + data.length() + ")")
end foreach

3. Repeat While

A repeat while loop evaluates its condition before each iteration and continues as long as the condition remains true. Parentheses are mandatory for clarity.

Theory

  • Pre-test Loop: The condition is checked before the body runs.
  • Dynamic Control: Ideal when the number of iterations depends on runtime conditions.

Syntax

repeat while (<condition>)
// code
end repeat

Example

set i to 1

repeat while (i <= 3)
show(i)
set i to i + 1
end repeat

// Using array.length() in the condition
declare values[]
set values to [5,6,7,8]

set idx to 0
repeat while (idx < values.length())
show(values[idx])
set idx to idx + 1
end repeat

4. Repeat Times

A repeat times loop executes the body a fixed number of times. It is essentially a for loop without exposing the counter.

Theory

  • Fixed Iteration: Specify exactly how many repetitions are needed.
  • Simple Syntax: Focus on the action rather than the counter.

Syntax

repeat n times
// code
end repeat

Example

repeat 3 times
show("Hello")
end repeat

5. Iterate Loop

An iterate loop offers a generic pattern similar to foreach but requires explicit parentheses. It is functionally the same as foreach over collections.

Theory

  • Explicit Declaration: Parentheses clarify the loop binding.
  • Versatile: Works with any iterable collection.

Syntax

iterate (item over collection)
// code using item
end iterate

Example

declare letters[]
set letters to ["a", "b", "c"]

iterate (letter over letters)
show(letter)
end iterate

6. Generate Loop

A generate loop is a customizable numeric loop terminated by the stop keyword instead of an explicit end generate. It provides flexibility to break out in the middle of the sequence.

Theory

  • Controlled Termination: Use stop to exit early.
  • Flexible Range: Define start, end, and step.

Syntax

generate i from start to end by step
// code using i
stop

Example

generate i from 1 to 5 by 2
show(i)
stop

7. Nested Loops

Loops can be nested to handle multi‑dimensional data or combined iteration patterns.

Theory

  • Inner Loop: Runs completely for each iteration of the outer loop.
  • Use Cases: Processing matrices, cross‑product of sets, or hierarchical data.

Examples

Nested For Loop

for i from 1 to 3
for j from 1 to 2
show("(" + i + "," + j + ")")
end for
end for

Nested Foreach and For

declare matrix[2]
set matrix to [[1,2], [3,4]]

for rowIndex from 0 to matrix.length() - 1
set row to matrix[rowIndex]
for colIndex from 0 to row.length() - 1
show("matrix[" + rowIndex + "][" + colIndex + "] = " + row[colIndex])
end for
end for

Nested Repeat While

set i to 1
repeat while (i <= 2)
set j to 1
repeat while (j <= 2)
show("(" + i + "," + j + ")")
set j to j + 1
end repeat
set i to i + 1
end repeat

8. Exiting and Skipping

Inside any loop you can alter its normal progression:

  • exit
    Immediately terminate the nearest enclosing loop.

  • skip
    Skip the remainder of the current iteration and continue with the next one.

Examples

for i from 1 to 5
if i == 3 then
exit
end if
show(i)
end for
for i from 1 to 5
if i == 3 then
skip
end if
show(i)
end for

Summary Table

Loop TypeSyntax ExampleKey Benefit
For Loopfor i from 1 to 5 [step n] ... end forPrecise numeric iteration
Foreachforeach x in coll ... end foreachReadable element-by-element traversal
Repeat Whilerepeat while (cond) ... end repeatPre-test loop for condition-based repetition
Repeat Timesrepeat n times ... end repeatFixed-count repetition
Iterate Loopiterate (x over coll) ... end iterateExplicit generic iteration
Generate Loopgenerate i from s to e by step ... stopNumeric iteration with early termination via stop
exitexitBreak out of the current loop immediately
skipskipSkip the rest of this iteration, continue with next one

Loops empower your programs to automate tasks, process dynamic data, and maintain clarity. Master these constructs to write efficient, scalable, and maintainable code.