3 - 31 3 - 31
MELSEC-Q
3 LET'S CREATE AND EXECUTE A PROGRAM
3.9 Using Subroutines
There are cases when a certain process is repeatedly performed within a program. For
example, if making a bar graph using the character " ,"
RUN
OK
10 READ A
20 FOR I=1 TO A
30 PRINT " " ;
40 NEXT I
50 PRINT
60 READ A
70 FOR I=1 TO A
80 PRINT " " ;
90 NEXT I
100 PRINT
110 DATA 5,9
120 END
The areas marked with are identically the same. If more graphs are to be created, a
long program may be required.
Subroutines are used to call the same process from various locations, treating them as
one "group." Namely, the GOSUB instruction and RETURN instruction are used.
Modify the program above so that it looks like as shown below.
RUN
OK
10 READ A
20 GOSUB 70
30 READ A
40 GOSUB 70
110 RETURN
50 DATA 5,9
60 END
70 FOR I=1 TO A
80 PRINT " " ;
90 NEXT I
100 PRINT
The execution result is the same, but the area marked with is now only one.
'GOSUB 70' in lines 20 and 40 calls the area that starts at line 70 ( Subroutine).
After the area ( Subroutine) is completed, the execution returns to where it left off
by the RETURN instruction in line 110.
The subroutine is used
by two instructions.
END
RUN
Subroutine
GOSUB 70
GOSUB 70
RETURN
RETURN
REMARK
Always use the GOSUB instruction to call subroutines. If the GOTO instruction is
used, an error will be generated at the RETURN instruction.