Loading...
An assembly loop must implement its own counter, condition and jump. Build a small trace to show that it terminates and performs the required number of updates.
What you'll be able to do
The program below accepts a non-negative integer n and outputs 1+2+...+n, provided the counter and sum fit the chosen LMC model. Input zero gives zero. sum starts at zero and counter stores n. The accumulator is repeatedly reloaded because each task reuses it for a different purpose.
At the top of each iteration, counter tells us how many positive terms remain. BRZ done checks the zero case before adding a term. The body adds counter to sum, stores the new sum, subtracts one from counter, stores it and branches back. Both stored values are needed because there is only one accumulator in this model.
For n=3, successive counter values at loop entry are 3, 2, 1 and 0. After the three bodies, sum is 3, then 5, then 6. The zero entry branches straight to done, where loading sum restores the value to be output. The accumulator may hold a counter or intermediate result during the loop; that is not necessarily the final answer.
A loop invariant can describe why the calculation works: sum contains the terms already removed from the countdown, while counter identifies the next term. Progress follows because every positive counter is reduced by one, and the allowed inputs eventually reach zero. Negative input would not meet that termination argument and is outside this program’s contract.
For input zero, no body should run and output should be zero. For input one, exactly one body should run and output should be one. If the zero check is moved after the body, the program may execute an unwanted update before discovering there is nothing to add. If STA counter is omitted, the stored counter never decreases.
When debugging, distinguish a wrong operation from a missing store or wrong branch target. Trace the program counter when a loop repeats unexpectedly. A mathematically correct sum can still overflow a limited mailbox, so the input contract includes a range bound. A simulator’s exact representation of out-of-range values should not be assumed to rescue an invalid input.
INP
STA counter
loop LDA counter
BRZ done
ADD sum
STA sum
LDA counter
SUB one
STA counter
BRA loop
done LDA sum
OUT
HLT
counter DAT 0
sum DAT 0
one DAT 1Scroll horizontally to see the full code or table.Attempt the task before opening its worked response. Record each change of state, explain the rule used, and check the result against the original requirements. Code examples labelled Python 3 use that language’s conventions; pseudocode states its own assumptions.
Common mistakes to avoid
Key takeaways
Test yourself
Answer a few questions, then review anything you missed.
Start with the quiz above to check the key ideas. You can also choose another topic from the practice library.