Loops

By: Chris (fog) Jeffels & Kevin Picone



I N D E X:






Loops, What are they?


     The various commands that make up the "Loop" family have a number of different uses and are an essential part of any program. Generally they are used to either loop a piece of code until a condition is met or simply to reduce the amount of code required by repeating a section of it.

     The first thing you'll notice about the various looping commands is that they work in pairs. They have a command to signify the beginning of a loop and another to signify the end, with anything falling between these two commands being looped. It is also worth noting that they can not be mixed so for example a loop starting with the REPEAT command must be closed with the UNTIL command and not the LOOP command.

     Anyway let's look at the options available, how we might implement them and why we may choose one type of loop over another. Please note the examples included are very basic so as to keep them as easy to understand as possible and also to limit the chances of including commands that the new user is not already familiar with.

Top






DO / LOOP


     The simplest loop there is, the DO/LOOP commands repeat a section of code an infinite number of times with no conditional checks. So a very basic example would look like this:

(Cut & Paste into editor - Press ESC to exit)
  
  Do
     Print "This is an infinite loop"
     Sync
  Loop
  


     This example simply repeats the PRINT command continuously until the program is interrupted. Whilst this is simplest of the loops, an infinite loop obviously has fairly limited uses within a proper program. To make it more flexible we have an EXITDO command that allows us to EXIT from the loop at any point. eg:

  
  Do
     Cls RGB(0,0,0)
     Print "Press any key"
     If ScanCode() Then ExitDo
     Sync
  Loop
  Print "We're out of the loop!"
  Sync
  Wait 3000
  


     So here the section of code between the DO and LOOP is repeated until a key is pressed then the program jumps to the first line after the LOOP command. Finally, as with the other loop types, it's worth noting that it is perfectly acceptable to jump outside of the loops to other sub-routines, psubs or functions. eg:

  
  Do
     Cls RGB(0,0,0)
     Gosub My_Sub
     My_Psub()
     Sync
  Loop
  
My_Sub:
  Print "This is my subroutine"
  Return
  
Psub My_Psub()
  Print "This is my Psub"
EndPsub
  


Top





DO / DECLOOP


     As we've already mentioned, the DO/LOOP repeats a section of code infinitely so the next step is to have a loop where we can control the number of times a section is repeated. The DO/DECLOOP is one such example. Here the code will be looped until a counter variable reaches zero, at which point the program will exit the loop and continue from the line following the DECLOOP command. Here's an example:

  
  CountDown=10
  Do
     Cls RGB(0,0,0)
     Print "This loop will self destruct in "+Str$(CountDown)
     Sync
     Wait 500
  DecLoop CountDown
  Print "Boom!"
  Print "Press any Key To End"
  Sync
  WaitKey
  



      As we can see, the code will continue looping until the variable "CountDown" reaches zero with its value decreasing by 1 each time the DECLOOP command is reached.

Also, as with the normal DO/LOOP, this loop can also be exited early using the EXIT or EXITDO command.

Top





REPEAT / UNTIL


      The next step logically is to be able to loop a section of code until a specified condition is met. That is the code contained between the two commands will be repeated until the outcome of a mathematical or logic test is true. eg:

  
  Repeat
     a=Rnd(9)
     b=Rnd(9)
     Print "a= "+Str$(a)+" and b= "+Str$(b)
     Sync
  Until a=b
  Print "We have a pair"
  Sync
  WaitKey
  


     So this section of code will be repeated until the values of the variables "a" and "b" are equal.

     Or a more typical game example could be:

  
  Repeat
   Rem Insert Your Game Code Here
  Until Players_Energy=0
  Print "You Died"
  


     The following are all examples of valid expressions:


UNTIL a=TRUE
UNTIL password$="playbasic"
UNTIL a^2<(SIN(b)*15.7)


     Again exiting from a REPEAT/UNTIL loop is possible at any time using the EXIT or EXITREPEAT command.

Top





WHILE / ENDWHILE


     Initially the WHILE/ENDWHILE may appear very similar to a REPEAT/UNTIL loop but there are a couple of crucial differences.

     REPEAT/UNTIL will loop a section of code until a certain condition is met where as a WHILE/ENDWHILE will loop the section while a certain condition is true. If we look at our previous typical game example we can see how this would differ:

  
  While Players_Energy>0
   Rem Insert Your Game Code Here
  EndWhile
  Print "You Died"
  


     So in the REPEAT/UNTIL example the loop would be repeated until the players energy reached zero but the WHILE/ENDWHILE example would loop while the player's energy was greater than zero. As you can see these two methods have the same effect by simply changing the conditional check involved but there is one other critical area where the two command sets differ. Code contained in a REPEAT/UNTIL structure will always be executed at least once where as in a WHILE/ENDWHILE structure it may never be executed. This is simply due to the location of the conditional check, one is at the start of the loop before the code is executed while the other is at the end and therefore after the loop has already been executed. Consider the following example:

  
  Check=1
  Repeat
     Print "Loop executed"
  Until Check=1
  


And now compare that with:

  
  Check=1
  While Check<>1
     Print "Loop executed"
  EndWhile
  


     As can be seen in the first example the PRINT command will be executed before the UNTIL command causes the loop to terminate but in the second example the WHILE command terminates the loop prior to the PRINT command being reached.

     Again the loop can be exited at any time with the EXITWHILE command.

Top





FOR / NEXT


     Arguably we now come to the most useful of the command sets, the FOR/NEXT loop. Closest in function to the DO/DECLOOP commands, although a lot more flexible, it allows a section of code to be repeated a controlled number of times. Let's look at a simple example that prints the numbers from 1 up to 10:

  
  For t = 3 To 10
     Print t
  Next t
  



     The first thing we notice is that the implementation of the FOR/NEXT commands is slightly more complicated than the other looping commands but when broken down it is fairly simple to understand.
The commands work by giving a variable an initial value and then each loop incrementing it's value by 1 until it reaches a specified value. So in our first example we are using the variable t to control the duration of our loop. It is given an initial value of 3 and will increase by 1 each time it reaches the NEXT command until it reaches 10. Note that reference to the variable after the NEXT command, in this case t, is optional but makes code easier to read when there are several loops within a single program.

     Another example shows how it can be used to handle multiple sprites. Here we create 20 different images and sprites that, without the FOR/NEXT loops would require the same code to be repeated 20 times over:

  
  Cls RGB(0,0,0)
  For s=1 To 20
     CircleC 20,20,20,1,RndRGB()
     GetImage s,0,0,40,40
     CreateSprite s
     SpriteImage s,s
     SpriteTransparent s,1
  Next s
  
  Counter=3000
  
  Do
     Cls RGB(0,0,0)
     
     For s=1 To 20
        PositionSprite s,(s*25),200+(100*Sin((s*10)+Counter))
     Next s
     
     DrawAllSprites
     Sync
  DecLoop Counter
  


     This example also clearly shows how loops can be nested within other loops of varying types. The main DO/DECLOOP is repeated 3000 times and during each execution the nested FOR/NEXT loop cycles through each of the 20 sprites updating their positions. A typical example of where this could be used is in a game is where you are required to display many bullets on screen. One FOR/NEXT loop could cycle through all our bullet sprites updating their on screen positions and checking for collisions etc.

     Another useful addition to the FOR/NEXT command set is the STEP command. Essentially this allows us to specify how much the control variable is altered by every loop if we need an amount other than the default increment of 1.


     Let us have another look at our previous DO/DECLOOP countdown example this time done using a FOR/NEXT loop.

  
  For CountDown=10 To 1 Step -1
     Cls RGB(0,0,0)
     Print "This loop will self destruct in "+Str$(CountDown)
     Sync
     Wait 500
  Next CountDown
  Print "Boom!"
  Sync
  WaitKey
  



     As you can see the STEP command is added to the end of the FOR command line and in this case tells PB to reduce the value of the CountDown variable by 1 each time the NEXT command. This will continue to decrease from it's initial value of 10 until it equals 1.

     And as with all the other command sets there is a command that allows us to exit a FOR/NEXT loop at any time. In this case it's called EXITFOR.

Top





HOW TO EXIT A LOOP


      Exit is general purpose way of ending the current loop so can therefore be used with all of the loop mechanisms mentioned above.

      Simply put it allows us to jump out of the current loop. Eg:

  
  For t=1 To 10
     If t=4 Then Exit
     Print t
  Next t
  
  Sync
  WaitKey
  


      In this example the program will loop through until it reaches the number "4". When it does, the IF statement will be TRUE, causing the program to EXIT the FOR/NEXT loop.

Top





CONTINUE


     One final command to be aware of that can be used with any of the loop command sets is the CONTINUE command. Simply put this allows us to jump to the end command in a loop. Eg:

  
  For t=1 To 10
     If t=4 Then Continue
     Print t
  Next t
  
  Sync
  WaitKey
  


     In this example the number 4 will never be printed as the CONTINUE command causes PB to jump straight to the NEXT command bypassing the PRINT.

Top



 
Related Info: ArrayBasics | Continue | Do | Exit | For | Functions&Psub | LinkedLists | NamingConventions | Operators | ProgramLayout | Repeat | Types | Variables | While :
 


(c) Copyright 2002 - 2024 - Kevin Picone - PlayBASIC.com