Loops

"I will not talk in class!"
"I will not talk in class!"
"I will not talk in class!"
"I will not talk in class!"
"I will not talk in class!"

You may have had to write similar things in school. Well, programming languages are designed to make repetitive events like this easy to write. The programming term "loop" means to reuse code multiple times in a row. You can repeat the code until a condition is true, until a condition is false, or a specified number of times.

FOR ... NEXT LOOP

When you need a section of code to be executed a certain number of times, use the FOR NEXT loop. This loop uses a variable often called a counter, which increases or decreases each time the loop is executed. The FOR statement gives a starting and ending value for the counter. When the counter reaches the ending value, the loop executes one more time. Here's the syntax:

FOR counter = startingValue to endingValue [STEP increment]
     [statements]
NEXT counter

So, instead of doing this:
MSGBOX 0, "Hello"
MSGBOX 0, "Hello"
MSGBOX 0, "Hello"
MSGBOX 0, "Hello"
MSGBOX 0, "Hello"

You could do the following:

FOR X = 1 to 3
     MSGBOX 0, "Hello"
NEXT X

Normally, a FOR NEXT loop goes through the counter values one number at a time. However, there are times when you might want to skip through the values at a different rate. The STEP keyword is used for this:

FOR X = 1 to 5 STEP 2
     MSGBOX 0, "Hello"
NEXT X

In this case, the message "Hello" will be displayed three times even though the counter goes up to five. And, the STEP keyword can be used to go through the values of counter in reverse.

FOR X = 3 to 1 STEP -1
     MSGBOX 0, "Hello"
NEXT X

Since "counter" is simply a variable, it can be used in the block of repeating code. This is extremely useful for sequential or pattern based events. Consider the following example:

DIM X AS INTEGER
DIM Message AS STRING 
FOR X = 1 to 5 STEP 2
     Message = "This is message number " + X + "."
     MSGBOX 0, Message
NEXT X