|
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.
If you run an infinite loop, you can stop it by pressing ALT+B
or closing the console window.
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.
DO/END DOSometimes you need to try something, check if it worked, and either continue or try again with helpful feedback. Traditional loops handle this awkwardly because the validation logic gets separated from the user interaction.
DO/END DO Solution:This construct runs once by default, but gives you clean control over whether to repeat with feedback:
This pattern is perfect for any "try until successful" scenario: file operations, user input, network connections, or data 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 = 1
Sets the starting value of the loop counter. This may be any numeric expression.
The starting value is required.
to 10
Defines the target value the counter moves toward.
The loop runs while the counter has not yet passed this value in the direction of the step.
The target value can be any numeric expression.
If omitted, the loop has no automatic end condition.
step 1
Specifies how the counter changes after each iteration. The step may be positive or negative and may be any numeric expression.
If omitted, the step defaults to 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. |