For
For <.counterVar.> = <.initialValue.> To <.finalValue.> [Step <.stepValue.>] ... Next [counterVar]
 
Parameters: NONE
Returns: NONE
 

      A For-Next, unlike a Repeat-Until or While-EndWhile loop, requires you to specify explicitly the number of iterations you want the loop to cycle through.

      At the start of the first iteration the InitialValue is assigned to the counter variable (integer type). At the end of each iteration the counter is increased by 1, or if an optional Step statement is given, by the stepValue.

      If the value of the counter variable is greater than the finalValue, PlayBASIC exits the loop. If the initialValue is greater than the finalValue, stepValue should be a negative number, so that the counter will be decreased. In this case PlayBasic exits the loop if the value of the counter variable is less than finalValue.



FACTS:


      * For-Next statements must be paired.

      * For-Next default to counting up from the start to end by one. If you want to count backwards or by a different value than one, then use the Step statement.

      * The counter variable may follow the Next statement, but is not necessary.

      * You can exit a For-Next loop anytime with the Exit or the ExitFor statement.

      * The For/Each/Next variant can be used to iterate through linked lists (Example bellow)





For / Next Example:



      Examples of For-Next Loops

  
; A simple For-Next loop
  For i = 1 To 4
     Print i
  Next i
  Sync
  
; A For-Next loop with a Step statement
  For i = 1 To 8 Step 2
     Print i
  Next i
  Sync
  
; A For-Next loop that goes down from 4 to 1
  For i = 4 To 1 Step -1
     Print i
  Next i
  Sync
  
  WaitKey
  


This code will output:

  
  1
  2
  3
  4
  1
  3
  5
  7
  4
  3
  2
  1
  





For Each (linked list) Example:


      Examples of For-Next Loops



  
; Declare a type of hold the information about our object
  Type tObject
     x#,y#          ; position
     Colour     ; colour
  EndType
  
; Declare a link list of objects
  Dim Object As tObject List
  
; --------------------------------------------
; Add 5 objects
; --------------------------------------------
  
  For lp=1 To 5
     
   ; Create and add a new TObject
   ; to head of Object list
     Object = New tobject
     
   ; init it's position
     Object.x#=Rnd(800)
     Object.y#=Rnd(600)
     
   ; init it's colour
     Object.Colour=RndRGB()
  Next
  
  
; --------------------------------------------
; draw the objects (as circles to the screen)
; --------------------------------------------
  
; use For EACH to iterate through the linked
; OBJECT() list
  For Each Object()
     
   ; draw this object as a filled circle of radius 10
     CircleC Object.x#,Object.y#,10,true,Object.Colour
  Next
  
  
  Sync
  WaitKey
  


 
Related Info: Continue | Do | Each | Exit | ExitFor | List | Loops | Next | Repeat | Step | Types | While :
 


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