Loop Statements

Top  Previous  Next

Emergence BASIC has many built in loop statements. Loop statements execute one or more lines of your program repeatedly until a condition is satisfied, or until all elements have been iterated.

FOR Statement

The FOR statement executes lines of code until a counter variable reaches a specified number. The NEXT statement determines the end of the loop.  The FOR statement has the syntax of:
 

FOR variable = start TO end {STEP skip}
   'Statements(s) to execute repeatedly
NEXT variable

The optional skip number tells EBASIC to count by a certain number. One NEXT statement is needed for each FOR statement. To better demonstrate look at this example:
 

OPENCONSOLE
DEF counter:INT
DEF name$:STRING 
INPUT "Enter your name ",name$
 
FOR counter = 1 TO 20 STEP 2
    PRINT "Hello ",name$
NEXT counter
 
PRINT "Press Any Key To Close"
DO:UNTIL INKEY$ <> ""
CLOSECONSOLE
END

Will print a greeting 10 times. The STEP 2 creates a loop that counts by twos until the counter variable is greater than or equal to 20. Once the counter has exceeded the end condition the loop ends. It is important to note that the loop includes the TO value.

To end a FOR/NEXT loop early use the BREAKFOR command.

DO and WHILE statements

The DO statement executes one or more statements in your program at least once and repeats them until the condition in the UNTIL statement is met. The DO statement has the syntax of:
 

DO
    'Statement(s) to exectute until condition = TRUE
UNTIL condition

The WHILE statement executes one or more statements in your program as long as the condition is met. The end of the loop is determined by the END WHILE statement. The WHILE statement has the syntax of:
 

WHILE condition
    'Statement(s) to execute while condition = TRUE
END WHILE

You can also use the pseudonym WEND in place of END WHILE.

If you examine the two statements, you will see that they are exact opposites of each other. The DO statement loops while a condition is false, the WHILE statement loops while a condition is true.
 

OPENCONSOLE
DEF x as INT
x=20
 
DO
   PRINT x
    x=x-1
UNTIL x < 11
 
WHILE x < 21
    PRINT x
    x=x+1
END WHILE
 
PRINT "Press Any Key To Close"
 
DO:UNTIL INKEY$ <> ""
CLOSECONSOLE
END

 

FOR EACH statement

A FOR EACH statement iterates through a linked list. It is fully documented in Using linked lists.