3 - 24 3 - 24
MELSEC-Q
3 LET'S CREATE AND EXECUTE A PROGRAM
3.6.3 Loop for the number of times specified
Use the FOR-NEXT instructions to execute certain instructions for a certain number of
times. Consider the following program.
10 FOR N=1 TO 5
20 PRINT N;
30 NEXT N
40 END
RUN
1 2 3 4 5
OK
The FOR-NEXT instructions
repeat the instructions between
the FOR and NEXT for a specified
number of times while changing
the value of one variable.
(Repeats 5 times)
Variable N doesn't necessarily have to increase by 1. It is also possible, for example, to
increase the value of variable N by 0.5 or to decrease it by 2. The rate of change can
be specified by the STEP instruction.
10 FOR N=2 TO 4 STEP 0.5
20 PRINT N;
30 NEXT N
RUN
2 2.5 3 3.5 4
OK
10 FOR N=5 TO 1 STEP -2
20 PRINT N;
30 NEXT N
RUN
5 3 1
OK
0.5
-2
0.5 0.5 0.5
-2
Do not use the GOTO instruction or IF-GOTO instruction to exit from instructions in
the loop created by the FOR-NEXT instructions or WHILE-WEND instructions. Doing
so may cause the CPU to run out of stack memory for the FOR-NEXT
and WHILE-WEND instructions, resulting in an "Out of memory" error.
FOR
Instructions
in the loop
NEXT
to
WHILE
WEND
to
Instructions
in the loop
REMARK
The NEXT instruction determines whether or not the loop will continue in the FOR-
NEXT instructions. Therefore, instructions between the FOR-NEXT instructions are
executed at least once, even in the FOR-NEXT instructions shown below.
10 FOR J=10 TO 1 STEP 2
20 PRINT " A"
30 NEXT J
RUN
A
OK
It is not possible to increase the value of J from 10 to 1
in step of 2, but the instruction of line 20 has already
been executed.