Square Triangles or Triangular Squares

Notice how we "get a triangular number" in three different places and the same goes for "get a square number".
This is where subroutines come in very handy.
A subroutine is a little program which we can jump to from anywhere.
The magic is that if we end the subroutine with the Return command (RTS),
we will be returned to where we came from.

LDA #1
STA TRI
STA SQ
LDA #2
STA TRAD
LDA #3
STA SQAD
LOOP: LDA TRI
SUB #9000
BPL END
LDA TRI
SUB SQ
BEQ GOT1
BMI NXTT
JSR GSQ
JMP LOOP
NXTT: JSR GTRI
JMP LOOP
GOT1: OUT TRI
JSR GSQ
JSR GTRI
JMP LOOP
GTRI: LDA TRI
ADD TRAD
STA TRI
INC TRAD
RTS
GSQ: LDA SQ
ADD SQAD
STA SQ
INC SQAD
INC SQAD
RTS
END: HLT

Assembler