Loop For Zero Times

RNovember

Well-known member
Hello, I just have a quick question that I need answered.
Is it possible to loop 0 times through a for loop?

I want my code to loop from 0 to a number in a variable, and if that number is 0, then do nothing.

This is the code I have so far:
Code:
flash:
    bPtr=28
    for b27=1 to 26
        pause 500
        for b27=1 to @bPtr
            pulsout C.2, 150
            pause 300
        next b27
        bPtr = bPtr + 1
    next b27
    goto main
This works except it flashes once for zero. Should I put an if statement in the loop to send it back to the beginning, or is there an easy way to loop 0 times?
 

techElder

Well-known member
First, you are reusing "b27" in both of your FOR/NEXT loops. The inner loop will reset the same variable in the outer loop.

You should investigate how a DO/LOOP works with WHILE and UNTIL.
 

hippy

Technical Support
Staff member
Is it possible to loop 0 times through a for loop?
No. The FOR part simple becomes a LET, sets the initial variable value, will execute the code within the FOR-NEXT, and only at the NEXT will it decide if it's going to repeat or not. Thus a FOR-NEXT will always execute at least once.

But you can make it have no effect by placing an IF-ENDIF around it or within it, or by writing the code some other way.

This will output "N" number of "X" characters to the Terminal, when "N" can be 0 or greater ...
Code:
SendX:
  Do While n > 0
    SerTxd( "X" )
    n = n - 1
  Loop
  Return
 

RNovember

Well-known member
No. The FOR part simple becomes a LET, sets the initial variable value, will execute the code within the FOR-NEXT, and only at the NEXT will it decide if it's going to repeat or not. Thus a FOR-NEXT will always execute at least once.
Thank you. That is what I needed to know.
First, you are reusing "b27" in both of your FOR/NEXT loops. The inner loop will reset the same variable in the outer loop.
I'll go and change my code. I have been having some bugs. Maybe this will fix it!
 

hippy

Technical Support
Staff member
If you have a list of numbers of flashes in b28 to b53, @bPtr from 28 to 53, then you should be able to achieve what you want with -
Code:
flash:
  for bPtr = 28 to 53
    pause 500
    if @bPtr > 0 Then
      for b27 = 1 to @bPtr
        pulsout C.2, 150
        pause 300
      next
    end if
  next
  goto main
 
Top