next up previous
Next: Decrement Until 0 Up: Example Programs Previous: Example Programs

Running Sum

The first example is a program to build a running sum of numbers. This program will loop forever accumulating a running total in memory location 2. The values shown in the code such as *sum* are values that will change during the running of the program. The value of *sum* will change by being written over, and the value of *num* is assumed to be either a constant value (so that the program adds the same number over and over again) or changed by some other means during program execution. Notice that because the data is all immediate, the program must modify its own code in order to update the value of *sum* (pretty ugly, I admit, but it's just a tiny machine).

The code, along with the memory location of each four-bit word, is as follows:

 
0		CLR		; Start with 0 in the accumulator

1 ADD ; load the current running total

2 *sum* ; held in location 2.

3 ADD ; Add the value of *num* to the

4 *num* ; current accumulator.

5 STORE ; Store the running sum back

6 2 ; into location 2 for the next iteration.

7 CLR ; Clear the accumulator to prepare to branch.

8 ADD ; load a 1 into the accumulator so

9 1 ; that the BNZ will always branch.

10 BNZ; Jump back to the start to add another

11 0 ; number to the running sum.

The instructions held in memory locations 7 through 11 force the BNZ to behave like an unconditional jump. The clear starts the accumulator at 0 so that the ADD 1 will leave a 1 in the accumulator. Now when the BNZ is executed, the accumulator is guaranteed not to be 0 and the branch is taken. This program will loop forever adding the value in memory location 4 to the running total stored in memory location 2.


next up previous
Next: Decrement Until 0 Up: Example Programs Previous: Example Programs

Erik Brunvand
Sat Nov 29 15:21:21 MST 1997