![]() |
B.4 Looping and FOR/NEXT |
Loops are one of the most powerful concepts in programming. They allow you to run the same block of code over and over again without rewriting it. This is essential for everything from counting to processing lists of data. Let's explore how loops work in SheerPower.
The simplest loop in SheerPower is the DO/LOOP
. It
repeats the code between the `DO` and `LOOP` keywords forever.
An infinite loop isn't very useful on its own. We need a way to control it.
Let's create a simple guessing game. The program needs to keep
asking for the magic word until the user guesses
it correctly. The UNTIL
statement is perfect for this.
Unlike many other languages, SheerPower allows you to place multiple `WHILE` (run while true) and `UNTIL` (run until true) conditions anywhere inside a `DO/LOOP`. This lets you create complex, multi-exit loops without messy `IF` statements.
SheerPower also offers a powerful DO/END DO
structure.
This block of code runs only once by default, but
gives you the ability to `EXIT DO` early or `REPEAT DO` to run the
block again. It is perfect for input validation.
When you know exactly how many times you need to repeat an
action, the FOR/NEXT
loop is the perfect tool.
It's designed specifically for counting.
i = 10
Where does the count start?
to 1
Where does the count end?
step -1
How do we count? (e.g., up by 1, down by 1)
Example: A Rocket Launch Countdown
Sometimes you need to handle special cases *inside* a loop.
ITERATE FOR
skips the rest of the
current loop run and moves immediately to the next item.
Example: Processing a To-Do List
DO/LOOP
when you don't know how
many repetitions you need.DO/END DO
for a single-pass
block that you can exit or repeat, great for validation.FOR/NEXT
when you need to
loop a specific number of times.
Hide Description
|
|
Enter or modify the code below, and then click on RUN |
Looking for the full power of Sheerpower?
Check out the Sheerpower website. Free to download. Free to use. |