Loop Structures

Loop structures allow you to execute a block of code repetitively.  The following loop structures are supported. 

Nesting Loops

For … Next loops

When you know how many times the loop is to execute, For Next loops come in very handy.  For Next loops use an index variable that increment or decrement in value on each repetition of the loop.

For index = start To end [Step increment]
 
 statements
Next
index

index is the variable you wish to use as the index variable
start
is the numerical starting value for index
end
is the numerical ending value for index

Step and increment are both optional.  If used, increment is the value to be added to the index upon each iteration.  If increment is positive, the index will count up.   if increment is negative, the index will count down.

The following loop will count from 2 to 10

For a = 2 to 10

Next a

When using an index variable of type uByte, counting down to 1 or up to 255 as follows will generate smaller faster code.

Dim x as uByte



For x=100 To 1 Step –1

Next x

For x=0 To 255

Next x

An Exit For statement will jump to the statement immediately following the corresponding Next statement, for early loop termination.

While … Wend Loops

While condition

  statements

 Wend

While condition is true execute the statements.

 The following example will count from 0 to 9 on an ASCII terminal

a="0"
While a<="9"
  Call putc(a): Call putc(" ")
  a=a+1
Wend

  

Repeat … End Repeat

Syntax:

Repeat count

  statements

End Repeat

count must be a literal where 0 < count < 257

Repeat statements count number of times.  A repeat loop is smaller and faster than a For Next, or a While Wend loop.

This example will send 10 period characters to the USART.

Repeat 10
  Call putc(".")
End Repeat



Nesting Loops

A control structure can be placed inside another control structure.  These structures can be “nested” as many levels as you like.

Sub nesting()
  Dim x as uByte
  Dim y as uByte
  Dim z as uByte

 

  For x=1 To 10
    For y=10 To 1 Step –1
      z=5
      While z>1
        z=z-1
      Wend
    Next y
  Next x
End Sub