Exercise 3: Counting Iterations Instead of Summing — Possible Solution ==================================================================== THE GOAL ------------------------------ Instead of accumulating a running sum in R2, count how many times the loop body runs before the counter (R1) reaches zero. Since the original loop decrements R1 by 1 each pass starting from N, the number of iterations that run is exactly N itself -- just arrived at by counting rather than by reading N back directly. MODIFIED LOOP ------------------------------ AND R2, R2, #0 ; R2 = iteration count = 0 LD R1, N ; R1 = counter = N LOOP ADD R2, R2, #1 ; iteration count++ ADD R1, R1, #-1 ; counter-- (also sets condition codes for R1) BRp LOOP ; loop while counter is still > 0 ST R2, ITERATIONS ... N .FILL #5 ITERATIONS .FILL #0 WHY THIS WORKS MECHANICALLY ------------------------------ Only two lines changed from the original loop: 1. The line that used to say "ADD R2, R2, R1" (add the counter's current value to the sum) is replaced with "ADD R2, R2, #1" (just add exactly 1 to the iteration count every pass, regardless of what R1's value happens to be that iteration). 2. The store target changed from SUM to ITERATIONS, since R2 no longer represents a sum. Everything else stays identical -- crucially, ADD R1, R1, #-1 still runs immediately before BRp with nothing in between, so BRp still correctly reads condition codes reflecting R1's new value each pass, exactly per this chapter's own condition-code discipline. The ADD R2, R2, #1 instruction, despite also writing a register, doesn't interfere, because it runs BEFORE the decrement, not between the decrement and the branch. WHY THIS WORKS AS AN ANSWER ------------------------------ It makes the minimal necessary change (swap the accumulation logic, rename the destination), preserves the original loop's condition-code discipline from this chapter (decrement immediately followed by branch), and explains why the result is mathematically equivalent to reading N directly -- counting to N one iteration at a time produces the same final value as N itself.