Repetition and Counters · Lesson 15 of 30 · about 12 minutes
Sum One to N
Keep an accumulator separate from the loop counter.
01 / Explain
Understand the idea
An algorithm is a repeatable method for solving a problem. To sum 1 through N, begin with total zero and add the current counter during each iteration. The total and counter serve different roles and need separate registers.
An invariant is a statement that remains true as the algorithm runs. After k iterations, the total is 1 + … + k. At zero iterations it is zero. Inspect this relation in the trace instead of guessing from the final answer.
02 / Try
Watch it happen
The running totals are 1, 3, 6, and 10. Only the final total is printed.
LOAD 1 R1
LOAD 0 R2
LOOP 4
LOAD R2
ADD R1
COPY R0 R2
LOAD R1
ADD 1
COPY R0 R1
RETURN
LOAD R2
PRINT
HALTUse Step to follow one instruction at a time. You can change the example and replay it.
03 / Challenge
Make it work
Read N from 0 through 10. Use a loop to print the sum 1 + 2 + … + N. Print 0 for N = 0.
The checker runs your current editor program in a fresh machine for each of 3 test cases. It supplies inputs and seeded memory itself; the lab’s current output and memory do not decide your result.
INPUT
COPY R0 R3
LOAD 1 R1
LOAD 0 R2
LOOP R3
# Add counter to total, then increment counter.
RETURN
LOAD R2
PRINT
HALTNeed a hint?
Reload R2 before adding R1, then save the new total back to R2.
Reveal a worked solution
Read the program, predict each instruction’s effect, then step through it in the lab.
INPUT
COPY R0 R3
LOAD 1 R1
LOAD 0 R2
LOOP R3
LOAD R2
ADD R1
COPY R0 R2
LOAD R1
ADD 1
COPY R0 R1
RETURN
LOAD R2
PRINT
HALTEmoji CPU lab
Emoji program
Type LOAD, ADD, or another opcode then Space to insert emoji. Ctrl/⌘ + Enter runs or pauses; Escape pauses; Ctrl/⌘ + ] indents. Tab moves focus. Labels use a colon. Jumps use zero-based instruction addresses.
Instruction map and breakpoints (0)
Breakpoints stop before an instruction. Run resumes past the stopped breakpoint once; Step executes it directly. Editing source clears old breakpoints and machine state.
CPU registers
- R0
- 0
- R1
- 0
- R2
- 0
- R3
- 0
- R4
- 0
- R5
- 0
- R6
- 0
- R7
- 0
Stacks and loop frames
SP = 255 − data depth − call depth. The stack is separate from memory.
Data stack (bottom → top)
Empty
Call return addresses (bottom → top)
Empty
Loop frames
Empty
Output and input
Run a PRINT instruction to see output.
Queued input: Empty
Memory · 256 bytes · 0 nonzero
Each cell shows address:value. R = read this step; W = written this step. Select a cell to inspect or initialize it before execution. Use arrow keys to move, Home/End for the row, and Ctrl/⌘ + Home/End for the whole memory.
Execution trace · 0 entries
Recent entries below. Inspect any zero-based index to see complete detached before/after state.
Check your challenge
You can run this check any time. Every case must pass to record completion.
Progress uses localStorage only. It stays on this browser and is never sent to a server.