This does pretty much the the same as the previous example but without wasting so many instruction cycles on NOOPs.
- NUM
0—1 - STR
0—2 - DUPE
0—3 - SUB
1—1 - BRANCH
4—1 - JUMP
4—3<-------------- NEW - NUMOUT
5—1 - STROUT
5—3 - NOOP
6—6
Before the loop we push a number to the stack to act as index. Each iteration we print the index and decrement it. When the index reaches 0, the BRANCH instruction will eventually break out of the loop. Only difference with last example is that we use JUMP instead of NOOPing back to the start.
- NUM
48(index) - LOOP_START: (address:
91)- DUPE
- NUMOUT
- STR
'\n'STROUT - DUPE
- NUM
1SUB - DUPE
- BRANCH
- true: push address
91(Address of LOOP_START) and JUMP to it <-------------- NEW - false: Continue after LOOP_END
- true: push address
- LOOP_END
- STR
'DONE'STROUT
. 0 . . . . . . . . . . . . . . . . . . . . . . . . . . .
|
. 1 . . . . . . . . . . . . . . . . . . . 3—4 0—6 1—1 1 .
|
. 1 . . . . . . . . . . . . . . . . . . . . . . . . . 0 .
|
. 0 6—6 0—3 5—1 0—2 1—0 1—3 0—0 5—3 0—1 0—1 1—1 0—3 4—1 .
. . . . . . . . . . . . . . . . . . . . . . . . . . . 0 .
|
. . . . . . . . 5 0—0 6—2 1—1 1—4 1—1 2—4 1—1 5—2 1—1 2 .
|
. . . . . . . . 3 . . . . . . . . . . . . . . . . . . . .
The JUMP instruction works with both direct addressing and labels. See next example for how to use labels.
