Home    Worksheets    Subroutines   
 

Help sheet 112:
For loops

This sheet shows you how to use Basic for loops

Suppose you want the  buggy to do a movement  7 times...



 

One way of doing this is to make a subroutine which does the movement you want, and call it  7 times with seven gosubs:

1)  7 Gosubs:
 
main:
'------- start of program
          gosub fwd
          gosub fwd
          gosub fwd
          gosub fwd
          gosub fwd
          gosub fwd
          gosub fwd
'----------end of main program---
                   
 
This program calls the fwd subroutine seven times in a simple straightforward way.

It takes longer to write.

It is not so easy to check whether you've done the right number.

It uses "gosub fwd" to run forwards. 
It calls it 7 times to go the required distance. 


Another is to use the built-in loop in Picaxe Basic called a "for" loop.

2)  for b0=1 to 7" and only one gosub:
 
main:
'------- start of program
          for b0=1 to 7
          gosub fwd
          next b0
'----------end of main program---

                   

 
The for loop starts by setting b0 to 1.

It increases b0 automatically each time round the loop

It exits the loop when b0 has reached the limit value (7)

The command  "for b0=1 to 7" sets b0 to 1 at the start of the loop
The
"next b0" increases b0 by 1.
The
"next b0" then checks whether b0 has reached the upper limit. If not it loops. 
The result is that whatever program is between the
"for"
and the "next" is repeated 7 times.


Content Scl Version 19/04/07